gpt4 book ai didi

javascript - 无法让 underscore.js 在没有语法错误的情况下使用花括号

转载 作者:行者123 更新时间:2023-12-03 12:19:51 26 4
gpt4 key购买 nike

有人知道为什么这行不通吗?我正在尝试让 _.template 使用大括号。

    _.templateSettings = { //change delimiter to <$ $>
interpolate : /\<\$(.+?)\$\>/g
};
var list = "<$ _.each(people, function(name) { $> <li><$ name $> </li> <$ }); $>";
var html=_.template(list);
console.log(html({people : ['moe', 'curly', 'larry']}));

它在 ) 处产生以下语法错误错误):

((__t=( .each(people, function(name) { ))==null?'':_t)+

Underscore 文档是这样说的:

If ERB-style delimiters aren't your cup of tea, you can change Underscore's template settings to use different symbols to set off interpolated code. Define an interpolate regex to match expressions that should be interpolated verbatim, an escape regex to match expressions that should be inserted after being HTML escaped, and an evaluate regex to match expressions that should be evaluated without insertion into the resulting string. You may define or omit any combination of the three. For example, to perform Mustache.js style templating:

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

var template = _.template("Hello {{ name }}!"); template({name : "Mustache"}); => "Hello Mustache!"

最佳答案

你的问题是插值的东西应该产生一个独立的 JavaScript 表达式,这个:

_.each(people, function(name) {

不是有效的表达式。您需要定义单独的evaluateinterpolate 正则表达式,然后将evaluate 用于_.each;像这样:

_.templateSettings = {
interpolate: /\{\{=(.+?)\}\}/g,
evaluate: /\{\{(.+?)\}\}/g,
};
var list = "{{_.each(people, function(name) {}} <li>{{=name}}</li> {{ }); }}";

请注意,插值现在使用 {{= ... }}{{ ... }} 仅用于评估(或嵌入)小的 JavaScript 片段。

演示:http://jsfiddle.net/ambiguous/SDmLz/

关于javascript - 无法让 underscore.js 在没有语法错误的情况下使用花括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17462069/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com