在 underscore.js 模板中使变量可选

发布于 2024-12-03 23:13:23 字数 593 浏览 0 评论 0原文

我有这样的代码:

_.templateSettings = {interpolate : /\{\{(.+?)\}\}/g};

var _d = _.template($('#_d').html());

$.get('/foo', function(data) {
    $('#output').html(_d(data));
});

在 HTML 中:

<div id="_d">
    {{name}} {{phone}}
</div>
<div id="output"></div>

/foo 返回类似于 {"name":"joe","phone":"12345"} 的内容,但有时它不会没有 phone 因此只会返回 {"name":"joe"},这将阻碍模板评估,因此在 output 中不会打印任何内容。如何使变量可选?

编辑: /foo 超出我的控制范围

I have this code:

_.templateSettings = {interpolate : /\{\{(.+?)\}\}/g};

var _d = _.template($('#_d').html());

$.get('/foo', function(data) {
    $('#output').html(_d(data));
});

and in HTML:

<div id="_d">
    {{name}} {{phone}}
</div>
<div id="output"></div>

/foo returns something like {"name":"joe","phone":"12345"}, but sometimes it doesn't have phone thus simply returns {"name":"joe"}, which will choke template evaluation thus nothing gets printed in output. How do I make a variable optional?

EDIT: /foo is beyond my control

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

霓裳挽歌倾城醉 2024-12-10 23:13:23

|| 运算符对于此类事情非常有用:

$.get('/foo', function(data) {
    data.phone = data.phone || "";
    $('#output').html(_d(data));
});

但是由于您已经在使用 Underscore,因此您可以使用 _.defaults 函数。这种方法对于为多个字段提供默认值特别有用:

$.get('/foo', function(data) {
    _.defaults(data, {name : 'joe', phone : ''});
    $('#output').html(_d(data));
});

The || operator is useful for this sort of thing:

$.get('/foo', function(data) {
    data.phone = data.phone || "";
    $('#output').html(_d(data));
});

But since you're already using Underscore, you can use the _.defaults function. This approach is particularly useful for providing defaults for multiple fields:

$.get('/foo', function(data) {
    _.defaults(data, {name : 'joe', phone : ''});
    $('#output').html(_d(data));
});
心如狂蝶 2024-12-10 23:13:23

我喜欢@namuol 解决方案,我们可以做的另一件事是在模型扩展中设置默认哈希

var MyModel = Backbone.Model.extend({
    defaults: {
        "foo": "I",
        "bar": "love",
        "yeah": "sara"
    }
});

只是另一个选项。

I liked @namuol solution, another thing that we could do is set the defaults hash at the model extends

var MyModel = Backbone.Model.extend({
    defaults: {
        "foo": "I",
        "bar": "love",
        "yeah": "sara"
    }
});

Just another option.

薔薇婲 2024-12-10 23:13:23

您可以有一个 html

<div id="d">
    {{data.name}} {{data.phone}}
</div>

使用如下模板来避免 phone 的未定义变量问题

_.templateSettings = {
  interpolate : /\{\{(.+?)\}\}/g
};

var template = _.template($('#d').html());
var jsonResponse = {"name":"Jeo"}; // phone is missing
var result = template({"data":jsonResponse});

You can have an html

<div id="d">
    {{data.name}} {{data.phone}}
</div>

Use the template as below to avoid undefined variable issue for phone

_.templateSettings = {
  interpolate : /\{\{(.+?)\}\}/g
};

var template = _.template($('#d').html());
var jsonResponse = {"name":"Jeo"}; // phone is missing
var result = template({"data":jsonResponse});
溺深海 2024-12-10 23:13:23

一个实用的解决方案是在对象中包含 phone,但值为空:


{"name":"joe","phone":""}

A practical solution would be to include phone in the object, but with an empty value:


{"name":"joe","phone":""}

羁客 2024-12-10 23:13:23

上面有一些很好的答案,但是您可以使用 _.partial 来获得应用具有默认值的模板的单个函数:

foobarTemplate = _.template('<%=foo%><%=bar%>')
barPrefilled = _.partial(_.defaults, _, {bar:'def'})
foobarTemplate(barPrefilled({foo:'abc'}))
//  "abcdef"
foobarTemplateWithDefaults = function (data) {return foobarTemplate(barPrefilled(data));}
foobarTemplateWithDefaults({foo:'wat'})
//  "watdef"
foobarTemplateWithDefaults({foo:'foo', bar:'bar'})
//  "foobar"

There are some good answers above, but you can use _.partial to get a single function that applies a template with defaults:

foobarTemplate = _.template('<%=foo%><%=bar%>')
barPrefilled = _.partial(_.defaults, _, {bar:'def'})
foobarTemplate(barPrefilled({foo:'abc'}))
//  "abcdef"
foobarTemplateWithDefaults = function (data) {return foobarTemplate(barPrefilled(data));}
foobarTemplateWithDefaults({foo:'wat'})
//  "watdef"
foobarTemplateWithDefaults({foo:'foo', bar:'bar'})
//  "foobar"
梦纸 2024-12-10 23:13:23

然后是显而易见的:将其放在模板的顶部:

<%
  if (typeof(phone) === "undefined") {
    phone = "";
  }
%>

工作片段:

$(function() {
  $('#result').html(
    _.template(
      $('#template').html(), {
        interpolate: /\{\{(.+?)\}\}/g
      }
    )({
      foo: 23,
      // No value for bar
      // bar: 11,
    },)
  )
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="x-template" id="template">
<%
  if (typeof(bar) === "undefined") {
    bar = "default";
  }
%>
This is {{ foo }} and {{ bar }}
</script>

<div id="result"></div>

(也如 jsfiddle

And then there is the obvious: Put this in the top of your template:

<%
  if (typeof(phone) === "undefined") {
    phone = "";
  }
%>

Working snippet:

$(function() {
  $('#result').html(
    _.template(
      $('#template').html(), {
        interpolate: /\{\{(.+?)\}\}/g
      }
    )({
      foo: 23,
      // No value for bar
      // bar: 11,
    },)
  )
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="x-template" id="template">
<%
  if (typeof(bar) === "undefined") {
    bar = "default";
  }
%>
This is {{ foo }} and {{ bar }}
</script>

<div id="result"></div>

(also as jsfiddle)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文