How to render a global variable as data inside for loop in the nunjucks?

434 Views Asked by At

I faced with a problem: I have global variables with SVG icons and I want to render all icons inside template using for loop. How to render a global variable as data inside for loop.

facebook: <svg viewBox="0 0 8 17" fill="none" xmlns="http://www.w3.org/2000/svg" .../>
{% set
 list = [
   {
     link: 'https://facebook-link',
     icon: 'facebook',
     title: 'facebook group',
   },
   {
     link: 'https://twitter-link',
     icon: 'twitter',
     title: 'twitter group',
   }
 ]
%}

<ul class="socials">
 {% for data in list %}
  <li class="socials__item">
    <a href="{{data.link}}" 
       title="{{data.title}}"
       target="_blank" 
       rel="noopener noreferrer nofollow"
       class="socials__link"
       >
     {{ data.icon | safe }}
    </a>
  </li>
  {% endfor %}
</ul>
1

There are 1 best solutions below

0
On

You can use a custom filter or global function to get the variable's value by its name

var nunjucks  = require('nunjucks');
var env = nunjucks.configure();

env.addFilter('context', function(variable) {
    return this.ctx[variable];
});

var html = env.renderString(
    `{{ 'facebook' | context | safe }}`, 
    {facebook: '<a href = "www.facebook.com">FB</a>'}
);

console.log(html);