Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nunjucks check for object or string

Tags:

nunjucks

How can I check if a variable is an object or string in an if block? It seems one can not call functions inside the {% if ... %} block. And the other {{ if() }} syntax seems only to be for inline conditions.

I solve it now to test for some object properties that should be there when the variable is an object, but there should be a better solution. Like an isObject or isString function

like image 828
Matthias Tylkowski Avatar asked Oct 20 '25 08:10

Matthias Tylkowski


2 Answers

You could use a custom filter:

var env = new nunjucks.Environment();

env.addFilter('is_string', function(obj) {
  return typeof obj == 'string';
});

This is what the template would look like:

{% 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>
like image 180
Ja͢ck Avatar answered Oct 23 '25 22:10

Ja͢ck


Custom filter or maybe you can...

if (string(foo) == foo) { // string }
else { // object }
like image 28
Félix Sanz Avatar answered Oct 24 '25 00:10

Félix Sanz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!