【问题标题】:String concatenation on if statement in underscore.jsunderscore.js 中 if 语句的字符串连接
【发布时间】:2016-06-18 21:40:24
【问题描述】:

我需要修改其他正在使用backbone.js 的代码。代码如下:

    var titleMovieTmpl = _.template('
        <h4 style="display: inline-block;">
            <%= item.title %> (<%= item.year %>)
        </h4>');

如何在此代码中添加 if 语句,例如:

<%= item.title %> if (<%= item.year %>){(<%= item.year %>)} 

到目前为止,我现在有:

var titleMovieTmpl = _.template('<h4 style="display: inline-block;"><%= item.title %>' <% if (item.year) { %> + '(<%= item.year %>)'<% } %> + '</h4><a href="javascript:void(0)" class="view-item">view title</a>');

但这给了我unexpected token % 的语法错误。以上是什么问题?

【问题讨论】:

标签: javascript backbone.js underscore.js underscore.js-templating


【解决方案1】:

在我看来,将模板分开会更易读,肯定是因为它变得更加复杂。它将解决您的引用/连接问题,并且您的 IDE 或编辑器也应该能够更好地处理它。

<script type='template' id='titleMovieTemplate'>
   <h4 style="display: inline-block;">
      <%= item.title %> 
      <% if (item.year) { %>
        (<%= item.year %>)
      <% } %>
   </h4>
</script>

之后,您可以在脚本中执行以下操作:

var titleMovieTmpl = _.template(document.getElementById('titleMovieTemplate').innerHTML);

【讨论】:

  • 谢谢你,这很有帮助,我已经能够成功地实现它。作为参考,您能否还请显示正确连接的字符串是什么?我已经工作了 15 分钟,但我无法让它匹配。
  • 是模板,不用拼接:'&lt;h4 style="display: inline-block;"&gt;&lt;%= item.title %&gt; &lt;% if (item.year) { %&gt; (&lt;%= item.year %&gt;) &lt;% } %&gt; &lt;/h4&gt;&lt;a href="javascript:void(0)" class="view-item"&gt;view title&lt;/a&gt;'
【解决方案2】:
<% if (item.year) { %> 
  (<%= item.year %>) 
<% } %>

【讨论】:

  • 谢谢,拆分字符串后,整个语句的外观如何?
  • @David542 没问题 :) 我不明白你的意思。你的例子中的字符串?
  • 基本上是整个变量定义(我更新问题的最后一部分)。使用正确的下划线if 语法看起来应该如何。
  • @David542 当然仍然必须是一个字符串 :) 仔细检查您的示例。
  • 您能详细说明一下吗?
猜你喜欢
  • 2011-11-12
  • 2021-12-18
  • 1970-01-01
  • 1970-01-01
  • 2012-01-27
  • 2017-01-15
  • 2016-12-03
  • 1970-01-01
  • 2018-03-09
相关资源
最近更新 更多