如何在Pug混入中正确输出传入的sliderSettings对象属性?
The issue is that Pug's #{} interpolation converts objects to their default string representation ([object Object]). To output the actual object properties, you need to serialize the sliderSettings object to a valid JSON string and use unescaped interpolation to avoid breaking the JavaScript syntax.
Here's the corrected mixin:
mixin slider({classes: {slider, arrows, arrow, dots, dot}, useArrows = false, useDots = false, dotsCounter}, sliderSettings = {}) div(class=['slider', slider].join(' ')) .glide__track(data-glide-el="track") ul.glide__slides block if useArrows div(class=arrows, data-glide-el="controls") span(class=['arrow-left', arrow].join(' '), data-glide-dir="<<") +icon({name: 'angle-left'}) span(class=['arrow-right', arrow].join(' '), data-glide-dir=">>") +icon({name: 'angle-right'}) if useDots div(class=['slider-dots', dots].join(' '), data-glide-el="controls[nav]") while i < dotsCounter span(class=['slider-dot', dot].join(' '), data-glide-dir="=" + i++) script new Glide('.#{slider}', !{JSON.stringify(sliderSettings)}).mount()
Key Changes Explained:
Added Default Value for
sliderSettings:
We setsliderSettings = {}in the mixin parameters to handle cases where no settings are provided, preventingJSON.stringify()from throwing an error.Replaced
#{sliderSettings}with!{JSON.stringify(sliderSettings)}:JSON.stringify(sliderSettings)converts your object into a valid JSON string that includes all its properties.!{}(unescaped interpolation) ensures the JSON string is rendered as-is in the script tag, without escaping quotes (which would break the JavaScript object literal).
Example Output:
If you call the mixin like this:
+slider( { classes: { slider: 'hero-slider' }, useDots: true, dotsCounter: 4 }, { type: 'carousel', perView: 1, autoplay: 5000, animationDuration: 800 } )
The resulting script tag will be:
<script> new Glide('.hero-slider', {"type":"carousel","perView":1,"autoplay":5000,"animationDuration":800}).mount() </script>
This works perfectly because JSON syntax is fully compatible with JavaScript object literals, so Glide will receive the exact settings object you passed.
内容的提问来源于stack exchange,提问作者WhoIsDT

