Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja2 - string variable with a space not reading correctly in classname

Tags:

flask

jinja2

I'm having an issue with Jinja2 not rendering the string 'fa fa-tachometer' correctly into the class name.

Jinja2 renders that string like this:

<i class={{ icon }}></i>

into

<i class="fa" fa-tachometer></i>,

as shown in the image below the code. I've done space literals but it doesn't fix the problem for me.

{% set navigation_bar = [
    ('/dashboard', 'dashboard', 'fa fa-tachometer', 'Dashboard')
] -%}
{% set active_page = active_page|default('dashboard') -%}

{# For each of the sidebar nav items, render an <li> #}
{% for href, id, icon, title in navigation_bar %}
    {{ icon }}
    <li {% if id == active_page %} class="active" {% endif %}>
        <a href="{{ href|e }}">
            <i class={{ icon }}></i>
            <span class="nav-label">{{ title|e }}</span>
        </a>
    </li>
{% endfor %}

enter image description here

Would love a solution to this. Thank you!

like image 201
Keith Yong Avatar asked Dec 02 '25 23:12

Keith Yong


1 Answers

This isn't a problem with Jinja; it's a problem with your HTML. You are telling Jinja to output

<i class=fa fa-tachometer></i>

(The DOM inspector you are using is adding the quotes, not Jinja. If you view the source HTML, they aren't there.)

You need to put quotes around the value given to class

<i class="{{ icon }}"></i>
like image 120
dirn Avatar answered Dec 05 '25 22:12

dirn