【问题标题】:Using mustache to fill in a html tag argument使用 mustache 填充 html 标记参数
【发布时间】:2011-11-15 13:59:55
【问题描述】:

我正在尝试使用 mustache 将标识符 (id) 附加到下面的 href

模板:

<div id='tmpl'>
    <a href='#product_detail?'{{id}}>link</a>
</div>    

var template = $('#tmpl').html();

数据:

var model = { id: 22 };

使用模型数据渲染模板:

var html = Mustache.to_html(template, model);

结果:

<a href="#product_detail?%7B%7Bid%7D%7D">link</a>

如果模板改为:

<div id='tmpl'>
    <a href='#product_detail?'{{id}}>link</a>
</div>

生成的模板是:

<a href="#product_detail?" 0="">link</a>

“问题”似乎是 jQuery 正在将模板中的单引号更改为混淆 mustache 的双引号。将小胡子标签放在引号之外也不会给出正确的结果。怎么解决?

谢谢

【问题讨论】:

    标签: jquery templates mustache


    【解决方案1】:

    你需要在href中添加{{id}},像这样:

    href="#product_detail?{{id}}"
    

    我们曾经将我们的小胡子模板放在 type="text/template" 的脚本中,我不知道它是否能解决您的转义问题,但我们这里没有。

    <script type="text/template" id="tmpl">
       <a href href="#product_detail?{{id}}">link</a>
    </script>
    

    如果您遇到一些转义问题,请在 id 之前使用 &:

    <script type="text/template" id="tmpl">
       <a href href="#product_detail?{{& id}}">link</a>
    </script>
    

    希望对您有所帮助!

    【讨论】:

    • @iRyusa "&" 选项到底有什么作用?
    • @wazz 谢谢!当我问这个问题时,这不可用:P
    【解决方案2】:

    我解决了这个问题,将 ${id} 放入属性而不是 {{id}} 例如:

    <button class="fisherytiles" type="button" data-myid="${Id}" id="imagelink">
    

    【讨论】:

      猜你喜欢
      • 2014-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多