您的位置:

对于django错误SyntaxError("Translation blocks must not include other block tags: ""%s (%sline %d)" % (t.contents, filemsg, t.lineno))的解决

  发布时间:2023-03-12 14:06:06
报错的原因这个错误消息通常是在 Django 模板翻译中出现的。例如,你可以使用下面的代码来翻译模板中的文本但是,在翻译模板的时候,Django 会扫描模板中的所有内容,确保翻译块不包含其他块标签。如果扫描到了这样的块,就会抛出 `SyntaxError` 错误。例如,你可以将上面的代码改为这样就不会抛出的错误了。希望这些信息能帮助你理解错误的原因,并解决这个问题。

报错的原因

`SyntaxError("Translation blocks must not include other block tags: ""%s (%sline %d)" % (t.contents, filemsg, t.lineno))` 这个错误消息通常是在 Django 模板翻译(template translation)中出现的。

在 Django 中,你可以使用模板翻译来在不同语言之间切换模板内容。例如,你可以使用下面的代码来翻译模板中的文本:


{% trans "Hello, World!" %}

但是,在翻译模板的时候,Django 会扫描模板中的所有内容,确保翻译块(translation block)不包含其他块标签(block tag)。如果扫描到了这样的块,就会抛出 `SyntaxError` 错误。

下面是一个例子,展示了如何出现 "Translation blocks must not include other block tags" 错误:


{% trans %}
    {% if user.is_authenticated %}
        Hello, {{ user.username }}!
    {% else %}
        Hello, World!
    {% endif %}
{% endtrans %}

在这个例子中,翻译块中包含了 `if` 和 `endif` 块标签,因此会抛出 `SyntaxError` 错误。

为了解决这个错误,你需要确保翻译块中不包含其他块标签。例如,你可以将上面的代码改为:


{% if user.is_authenticated %}
    {% trans "Hello, {{ user.username }}!" %}
{% else %}
    {% trans "Hello, World!" %}
{% endif %}

这样就不会抛出 "Translation blocks must not include other block tags" 的错误了。

希望这些信息能帮助你理解 "Translation blocks must not include other block tags" 错误的原因,并解决这个问题。

如何解决

要解决 "Translation blocks must not include other block tags" 的错误,你需要确保翻译块中不包含其他块标签。

例如,如果你的模板代码如下:


{% trans %}
    {% if user.is_authenticated %}
        Hello, {{ user.username }}!
    {% else %}
        Hello, World!
    {% endif %}
{% endtrans %}

那么你需要将代码改为:


{% if user.is_authenticated %}
    {% trans "Hello, {{ user.username }}!" %}
{% else %}
    {% trans "Hello, World!" %}
{% endif %}

这样就不会抛出 "Translation blocks must not include other block tags" 的错误了。

希望这些信息能帮助你解决 "Translation blocks must not include other block tags" 的问题。

使用例子

下面是一个使用翻译块的例子,在这个例子中没有出现 "Translation blocks must not include other block tags" 的错误:


{% if user.is_authenticated %}
    {% trans "Hello, {{ user.username }}!" %}
{% else %}
    {% trans "Hello, World!" %}
{% endif %}

在这个例子中,翻译块中只包含了翻译字符串,没有包含其他块标签。