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

标签 javascript lodash template-engine

我正在使用 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 <% if (typeof(headline) !== "undefined") { %> 中的语句.但是当我简单地写 <% if (headline) { %> ,它会说标题未定义。

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

最佳答案

尝试访问 JavaScript 中 undefined variable 将导致异常除非您使用typeof。没有真正的解决办法。

但是,如果您将整个模板包装在另一个对象中,则可以按照您想要的方式使用 if(因为对象缺少属性会导致 undefined ,也不异常(exception)):

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

...

关于javascript - 使用 lodash 模板,如何检查变量是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40534616/

相关文章:

javascript - 如何完全禁用任何鼠标单击

javascript - JS : Keep variable values for onclick event attached inside for loop

javascript - 在内容页面上触发 .Net 中的 OnLoad Javascript

javascript - 如何使用 Lodash 在 map 中从 1 个元素中生成 2 个元素

python - 国际化 html 模板的性能

javascript - Node.js 发送空字体文件

node.js - 为什么我似乎无法将普通对象合并到 Mongo Document 中?

javascript - 如何将(对象的)数组分区或划分为特定数量的 block ,可能使用 lodash

smarty - Smarty 和 Template Toolkit 有共同的交集吗?

Java : Applying a Velocity script dynamically