Nunjucks: Helper functions to check type of a variable

Created on 24 Apr 2015  路  2Comments  路  Source: mozilla/nunjucks

It seems there are no helper functions to check the basic types if variables like isObject, isString ...

Most helpful comment

For posterity, what @ArmorDarks meant was create filters in plain JS:

// typeof for a plain object, using Lodash:
environment.addFilter('isObj', something => _.isPlainObject(something))

// typeof for array, using native JS Array.isArray()
environment.addFilter('isArr', something => Array.isArray(something))

All above is happening in Gulp which is rendering Nunjucks using gulp-nunjucks-render. Nunjucks custom environment (for example manageEnvironment below) which you provide to the Nunjucks renderer would be like:

.pipe(nunjucksRender({
  path: ['templates'],
  manageEnv: manageEnvironment,
  envOptions: {
    throwOnUndefined: false,
  },
}))

Then, anywhere in Nunjucks templates just pipe the variable into your custom typeof filter:

{%- if (name_of_variable_which_type_you_want_to_check | isArr) -%}

Just follow the documentation how to set up Nunjucks filter and tweak the Nunjucks environment.

All 2 comments

See why it isn't there and probably won't be in future here https://github.com/mozilla/nunjucks/pull/263

You can configure your own filters with typeof checks as per https://mozilla.github.io/nunjucks/api.html#custom-filters

For posterity, what @ArmorDarks meant was create filters in plain JS:

// typeof for a plain object, using Lodash:
environment.addFilter('isObj', something => _.isPlainObject(something))

// typeof for array, using native JS Array.isArray()
environment.addFilter('isArr', something => Array.isArray(something))

All above is happening in Gulp which is rendering Nunjucks using gulp-nunjucks-render. Nunjucks custom environment (for example manageEnvironment below) which you provide to the Nunjucks renderer would be like:

.pipe(nunjucksRender({
  path: ['templates'],
  manageEnv: manageEnvironment,
  envOptions: {
    throwOnUndefined: false,
  },
}))

Then, anywhere in Nunjucks templates just pipe the variable into your custom typeof filter:

{%- if (name_of_variable_which_type_you_want_to_check | isArr) -%}

Just follow the documentation how to set up Nunjucks filter and tweak the Nunjucks environment.

Was this page helpful?
0 / 5 - 0 ratings