You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jinja2字符串内引用变量问题:双语文档宏使用难题

Fixing Jinja2's select_lang Macro Issues with Variable Inputs

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., &lt;i&gt; instead of <i>), add the safe filter 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:09:01