简体   繁体   English

使用lodash模板,如何检查变量是否存在?

[英]Using lodash templates, how can I check if a variable exists?

I'm using Lodash templates. 我正在使用Lodash模板。


Template: 模板:

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


Data to provide to template: 提供给模板的数据:

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


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


The approach I have written above (from: https://stackoverflow.com/a/7230755/83916 ) works well, but I really don't like the if statements as in <% if (typeof(headline) !== "undefined") { %> . 我上面编写的方法(来自: https : //stackoverflow.com/a/7230755/83916 )很好用,但是我真的不喜欢if语句,如<% if (typeof(headline) !== "undefined") { %> But when I simply write <% if (headline) { %> , it will say that headline is undefined. 但是当我简单地写<% if (headline) { %> ,它将说标题是未定义的。

Is there a more simple way to check if a variable exists using lodash templates that will not clutter up the html? 有没有更简单的方法来使用lodash模板检查变量是否存在,而不会使html变得混乱?

Trying to access an undefined variable in JavaScript will result in an exception unless you use typeof . 除非使用typeof 否则尝试在JavaScript中访问未定义的变量将导致异常。 There is no real way around that. 没有真正的解决办法。

However, if you wrap your whole template in another object, then using an if the way you want should work (as a property missing on an object results in undefined , not an exception): 但是,如果将整个模板包装在另一个对象中,则使用if所需的方式工作(因为对象缺少属性会导致undefined ,而不是异常):

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

And then in your template: 然后在您的模板中:

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

...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM