Skip to content
This repository has been archived by the owner on Feb 26, 2024. It is now read-only.

Commit

Permalink
Add global nunjucks function - icon
Browse files Browse the repository at this point in the history
  • Loading branch information
alsolovyev committed Apr 23, 2021
1 parent e26b808 commit 90e8777
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
13 changes: 13 additions & 0 deletions config/modules/njk-loader/functions/icon.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/**
* Simplifies work with SVG sprite.
*
* @param {string} name - SVG icon name
* @returns {string}
*
* @example
* 1. Import SVG ivon (app.js)
* import '@/icons/heart.svg'
* 2. Use it in nunjucks template (template.njk)
* <div>{{ icon('heart') | safe }}</div>
*/
module.exports = name => `<svg class='icon'><use xlink:href="#${name}"></use></svg>`
4 changes: 4 additions & 0 deletions config/modules/njk-loader/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const path = require('path')
const { Environment, FileSystemLoader } = require('nunjucks')
const schema = require('./schema')
const iconFn = require('./functions/icon')


/**
Expand Down Expand Up @@ -30,6 +31,9 @@ module.exports = function(source) {
this.addDependency(source.path)
})

// Add a global value that will be available to all templates.
env.addGlobal('icon', iconFn)

env.renderString(source, context, (error, HTMLString) => {
callback(error ? error : null, HTMLString)
})
Expand Down

0 comments on commit 90e8777

Please sign in to comment.