【问题标题】:How to call standard javascript functions inside Swig template?如何在 Swig 模板中调用标准 javascript 函数?
【发布时间】:2014-01-28 19:38:05
【问题描述】:

具体我想打电话给{% if typeof(myvar) == "boolean" %}{% set a = parseInt(myvar) %},但现在它给出了这个错误:

SyntaxError: Unexpected token !== at Object.Function () at Object.precompile (/home/aidan/Desktop/nodejs/turbo/node_modules/swig/lib/swig.js:465:11) 在 Object.compile (/home/aidan/Desktop/nodejs/turbo/node_modules/swig/lib/swig.js:560:16) 在 Function.exports.swig.render (/home/aidan/Desktop/nodejs/turbo/node_modules/consolidate/lib/consolidate.js:246:56) 在 /home/aidan/Desktop/nodejs/turbo/node_modules/consolidate/lib/consolidate.js:146:25 在 /home/aidan/Desktop/nodejs/turbo/node_modules/consolidate/lib/consolidate.js:99:5 在 fs.js:266:14 在 Object.oncomplete (fs.js:107:15)

【问题讨论】:

  • Swig 似乎解析了您的表达式并且无法处理 typeof (看起来像一个函数,但不是)。 set 声明应该可以工作。你想完成什么?
  • 好吧,我正在向模板传递一个值并想检查它是否是一个数组,如果是 - 检查数组是否包含所需的键:if typeof myvar == "object" and myvar.indexOf(anothervar)
  • Swig 不是 JavaScript。不支持这些功能。

标签: javascript node.js express swig-template


【解决方案1】:

您可以定义一个过滤器,然后编写一个set 语句,并将过滤器应用于变量。最后,您可以在 if 语句中使用此变量。

例如:

swig.setFilter('isObject', function(element) {
  return typeof element == "object";
});

然后:

{% set elementIsObject = myvar|isObject %}
{% if elementIsObject %} ... {% endif %}

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2011-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    相关资源
    最近更新 更多