【问题标题】:Printing variables within Underscore template ternary在下划线模板三元中打印变量
【发布时间】:2017-02-01 17:41:50
【问题描述】:

是否可以在评估期间在下划线模板中打印变量。

<a href="<%=data.active ? 'the/url' : 'another/url/<%='data.id'%>'%>">Link with printed parameter</a>

这给了我一个意外的标识符错误。我已经尝试在第二个 %&gt; 周围使用各种 excapings,但它只是按字面意思打印。我也尝试过使用print() 别名,这样编译器就不会被重复的%&gt; 弄糊涂,但是没有运气。有没有办法在三元组中做到这一点?

【问题讨论】:

    标签: javascript underscore.js lodash template-engine


    【解决方案1】:

    当您不尝试使用嵌套模板时,可以正常工作。

    var source = document.getElementById("testTemplate").innerHTML;
    var testTemplate = _.template(source);
    
    document.getElementById("target1").innerHTML = testTemplate({
      data: {
        active: false,
        id: 12345
      }
    });
    
    document.getElementById("target2").innerHTML = testTemplate({
      data: {
        active: true,
        id: 67890
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
    
    <script type="text/template" id="testTemplate">
      <a href="<%= data.active ? 'the/url' : 'another/url/' + encodeURIComponent(data.id) %>">Link with printed parameter</a>
      <p>The URL is "<%= data.active ? 'the/url' : 'another/url/' + encodeURIComponent(data.id) %>".</p>
      <hr>
    </script>
    
    <div id="target1"></div>
    <div id="target2"></div>

    注意:即使您的data.id 通常是严格的数字,在构建 URL 时最好还是使用encodeURIComponent。干净地转义数据是一个好习惯。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多