Jinja2字符串内引用变量问题:双语文档宏使用难题
Let’s walk through getting your select_lang macro working smoothly with Jinja2 variables—this is a common spot folks trip up, but it’s easy to fix once you know the right syntax.
First, let’s make sure your macro is defined correctly to accept dynamic inputs. Here’s a clean, functional version that handles both static strings and variables:
{% macro select_lang(main_lang_text, secondary_lang_text) %} {{ main_lang_text }} / <i>{{ secondary_lang_text }}</i> {% endmacro %}
Using Variables with the Macro
Suppose you’ve got Jinja variables set up (either via {% set %} or passed into your template context):
{% set greeting_en = "Hello" %} {% set greeting_fr = "Bonjour" %}
To call the macro with these variables, just pass the variable names directly—don’t wrap them in quotes (that would pass the literal string "greeting_en" instead of its value):
{{ select_lang(greeting_en, greeting_fr) }}
This will output exactly what you want:Hello / <i>Bonjour</i>
Common Pitfalls to Check
If you’re still having issues, here are the most likely culprits:
- Accidental Quoting: If you wrote
select_lang("greeting_en", "greeting_fr"), you’re passing literal strings instead of variable values. Ditch the quotes for variables. - Undefined Variables: If you see an
UndefinedError, double-check that your variables are declared (with{% set %}) or properly passed into the template before calling the macro. - HTML Escaping: If your secondary language text includes HTML that’s getting escaped (e.g.,
<i>instead of<i>), add thesafefilter to the variable in the macro—just be careful if the content comes from user input (to avoid XSS risks):{% macro select_lang(main_lang_text, secondary_lang_text) %} {{ main_lang_text }} / <i>{{ secondary_lang_text|safe }}</i> {% endmacro %} - Syntax Errors: Make sure all your template tags (like
{% set %}) are properly closed with%}and that the macro is defined before you try to call it in your template.
内容的提问来源于stack exchange,提问作者NiklasR

