Nunjucks 检查对象或字符串
Nunjucks check for object or string
如何检查 if 块中的变量是对象还是字符串?
似乎无法调用 {% if ... %}
块内的函数。
而其他 {{ if() }}
语法似乎仅适用于内联条件。
我现在解决它是为了测试当变量是一个对象时应该存在的一些对象属性,但是应该有更好的解决方案。像 isObject
或 isString
函数
自定义过滤器或者您可以...
if (string(foo) == foo) { // string }
else { // object }
您可以使用 custom filter:
var env = new nunjucks.Environment();
env.addFilter('is_string', function(obj) {
return typeof obj == 'string';
});
模板应该是这样的:
{% if item|is_string %}yes{% endif %}
var env = new nunjucks.Environment();
env.addFilter('is_string', function(obj) {
return typeof obj == 'string';
});
var res = env.renderString("{% if item|is_string %}yes{% endif %}", { item: 'test' });
document.body.innerHTML = res;
<script src="https://mozilla.github.io/nunjucks/files/nunjucks.js"></script>
您可以使用 built-in 字符串测试:
{% if foo is string %}
It is a string
{% endif %}
是-关键字将条件标记为nunjucks/jinja-test。 字符串这个词指的是built-in测试
查看测试 jinja-description:
- https://jinja.palletsprojects.com/en/3.0.x/templates/#tests
- https://jinja.palletsprojects.com/en/3.0.x/templates/#builtin-tests
Nunjucks 是 inspired by jinja2。我还没有找到关于测试的 nunjucks-documentation,但是字符串测试有效。
如何检查 if 块中的变量是对象还是字符串?
似乎无法调用 {% if ... %}
块内的函数。
而其他 {{ if() }}
语法似乎仅适用于内联条件。
我现在解决它是为了测试当变量是一个对象时应该存在的一些对象属性,但是应该有更好的解决方案。像 isObject
或 isString
函数
自定义过滤器或者您可以...
if (string(foo) == foo) { // string }
else { // object }
您可以使用 custom filter:
var env = new nunjucks.Environment();
env.addFilter('is_string', function(obj) {
return typeof obj == 'string';
});
模板应该是这样的:
{% if item|is_string %}yes{% endif %}
var env = new nunjucks.Environment();
env.addFilter('is_string', function(obj) {
return typeof obj == 'string';
});
var res = env.renderString("{% if item|is_string %}yes{% endif %}", { item: 'test' });
document.body.innerHTML = res;
<script src="https://mozilla.github.io/nunjucks/files/nunjucks.js"></script>
您可以使用 built-in 字符串测试:
{% if foo is string %}
It is a string
{% endif %}
是-关键字将条件标记为nunjucks/jinja-test。 字符串这个词指的是built-in测试
查看测试 jinja-description:
- https://jinja.palletsprojects.com/en/3.0.x/templates/#tests
- https://jinja.palletsprojects.com/en/3.0.x/templates/#builtin-tests
Nunjucks 是 inspired by jinja2。我还没有找到关于测试的 nunjucks-documentation,但是字符串测试有效。