You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pug混入中正确输出传入的sliderSettings对象属性?

Solution

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:

  1. Added Default Value for sliderSettings:
    We set sliderSettings = {} in the mixin parameters to handle cases where no settings are provided, preventing JSON.stringify() from throwing an error.

  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 12:42:41