jinja2.exceptions.TemplateSyntaxError: expected token 'end of print statement', got 'dark'

jinja2.exceptions.TemplateSyntaxError: expected token 'end of print statement', got 'dark'

我是编程新手。我不明白为什么会出现这个错误。为什么在 'Dark' 中出现错误。 <header id="header" class='{% if nav_style == "Light Version" %}{{ full-header }}{% endif %} {% if nav_style == "Dark Version" %}{{ full-header dark }}{% endif %} {% if nav_style == "Transparent" %}{{ transparent-header dark }}{% endif %} {% if nav_style == "Semi Transparent Light Version" %}{{ full-header transparent-header semi-transparent }}{% endif %} {% if nav_style == "Semi Transparent Dark Version" %}{{ full-header transparent-header semi-transparent dark }}{% endif %} {% if nav_style == "Floating Version" %}{{ full-header transparent-header floating-header }}{% endif %} {% if nav_style == "Static Sticky "%}{{ full-header }}{% endif %} {% if nav_style == "Responsive Sticky" %}{{ full-header }}{% endif %}' {% if nav_style == "Static Sticky" %}data-sticky-shrink="false"{% endif %} {% if nav_style == "Responsive Sticky" %}data-mobile-sticky="true"{% endif %} >

当您使用 {{ varname }} 语法时,Jinja2 期望 varname 是一个有效的变量名称,您将其作为上下文变量传递给渲染函数。在渲染期间,Jinja2 将用 varname 的值替换此术语。但是在您的模板中,您只是 select 一些 class 名称,它们是基于 nav_style 值的简单字符串。因此您不必使用 {{ ... }} 语法,因为它们不是变量,而是模板中的简单字符串。所以这样的事情应该有效:

<header id="header"
    class='{% if nav_style == "Light Version" %} full-header {% endif %} 
        {% if nav_style == "Dark Version" %} full-header dark {% endif %} 
        {% if nav_style == "Transparent" %} transparent-header dark {% endif %} 
        {% if nav_style == "Semi Transparent Light Version" %} full-header transparent-header semi-transparent {% endif %} 
        {% if nav_style == "Semi Transparent Dark Version" %} full-header transparent-header semi-transparent dark {% endif %} 
        {% if nav_style == "Floating Version" %} full-header transparent-header floating-header {% endif %} 
        {% if nav_style == "Static Sticky "%} full-header {% endif %} 
        {% if nav_style == "Responsive Sticky" %} full-header {% endif %}'
    {% if nav_style=="Static Sticky" %}data-sticky-shrink="false" {% endif %} 
    {% if nav_style=="Responsive Sticky" %}data-mobile-sticky="true" {% endif %}>

但是这个模板内部逻辑太多,阅读和调试都比较困难。您应该将此逻辑放在视图函数中,并将 selected class 名称作为简单变量传递,例如nav_style_classes:

<header id="header" class="{{ nav_style_classes }}" 
    {% if nav_style=="Static Sticky"%}data-sticky-shrink="false" {% endif %} 
    {% if nav_style=="Responsive Sticky" %}data-mobile-sticky="true" {% endif %}>