【问题标题】:Using lodash templates, how can I check if a variable exists?使用 lodash 模板,如何检查变量是否存在?
【发布时间】:2017-03-24 21:29:09
【问题描述】:

我正在使用 Lodash 模板。


模板:

<script type="text/template" id="example-template">
  <% if (typeof(leadingIconClass) !== "undefined") { %>
    <span class="glyphicon glyphicon-<%= leadingIconClass %>" aria-hidden="true"></span>
  <% } %>

  <% if (typeof(headline) !== "undefined") { %>
    <strong><%= headline %></strong>
  <% } %>

  <%= message %>

  <% if (typeof(mainHTML) !== "undefined") { %>
    <div class="group" style="margin-top: 20px;">
      <%= mainHTML %>
    </div>
  <% } %>
</script>


要提供给模板的数据:

var data = {
  message: 'Are you sure?'
};


编译模板并附加到容器:
$container.prepend(_.template($("#example-template").html())(data));


我上面写的方法(来自:https://stackoverflow.com/a/7230755/83916)效果很好,但我真的不喜欢if 中的&lt;% if (typeof(headline) !== "undefined") { %&gt; 语句。但是当我简单写&lt;% if (headline) { %&gt;时,它会说标题是未定义的。

有没有更简单的方法来检查变量是否存在,使用不会弄乱 html 的 lodash 模板?

【问题讨论】:

    标签: javascript lodash template-engine


    【解决方案1】:

    尝试访问 JavaScript 中未定义的变量将导致异常除非您使用typeof。没有真正的解决办法。

    但是,如果您将整个模板包装在另一个对象中,那么使用 if 应该是您想要的工作方式(因为对象上缺少属性会导致 undefined,而不是例外):

    var data = {
      data: {
        message: 'Are you sure?'
      }
    };
    

    然后在你的模板中:

    <script type="text/template" id="example-template">
      <% if (data.leadingIconClass) { %>
        <span class="glyphicon glyphicon-<%= data.leadingIconClass %>" aria-hidden="true"></span>
      <% } %>
    
    ...
    

    【讨论】:

    • 另一种可能性&lt;span class="glyphicon &lt;%= data.leadingIconClass ? 'glyphicon-' + data.leadingIconClass : '' %&gt;" aria-hidden="true"&gt;&lt;/span&gt; 这允许您跳过if 条件
    • 这不会产生相同的效果,因为最初的想法是在该变量不存在时根本不显示&lt;span&gt;
    猜你喜欢
    • 2010-09-23
    • 2011-07-01
    • 1970-01-01
    • 2020-05-30
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 2010-10-25
    • 2012-10-07
    相关资源
    最近更新 更多