From fb1f355877eb2537dd83c5c407a466a0e97939ce Mon Sep 17 00:00:00 2001 From: leon Date: Mon, 10 Aug 2026 23:13:27 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E5=85=B3=E4=BA=8E?= =?UTF-8?q?=E6=88=91=E4=BB=AC=E5=A4=9A=E8=AF=AD=E8=A8=80=E5=88=87=E6=8D=A2?= =?UTF-8?q?=E5=92=8C=E8=AF=AD=E8=A8=80=E5=88=87=E6=8D=A2=E6=8C=89=E9=92=AE?= =?UTF-8?q?=E5=9B=9E=E9=80=80=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/core/templatetags/i18n_tags.py | 28 +++++++++++++++++++++++++--- templates/core/about.html | 4 ++-- templates/includes/header.html | 1 + 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/apps/core/templatetags/i18n_tags.py b/apps/core/templatetags/i18n_tags.py index 9344b15..1941684 100644 --- a/apps/core/templatetags/i18n_tags.py +++ b/apps/core/templatetags/i18n_tags.py @@ -4,8 +4,30 @@ from django.utils.translation import get_language register = template.Library() -@register.simple_tag -def ml_field(obj, field_name): +def _ml_value(obj, field_name): + """根据当前语言返回 obj 的 _zh 或 _en 字段值。""" + if obj is None: + return '' lang = get_language() suffix = 'en' if lang.startswith('en') else 'zh' - return getattr(obj, f'{field_name}_{suffix}', '') or getattr(obj, f'{field_name}_zh', '') + val = getattr(obj, f'{field_name}_{suffix}', '') or '' + if not val: + # 找不到对应语言内容时回退到中文 + val = getattr(obj, f'{field_name}_zh', '') or '' + return val + + +@register.simple_tag +def ml_field(obj, field_name): + return _ml_value(obj, field_name) + + +@register.filter +def ml(obj, field_name): + """过滤器形式,可在 with、变量赋值、管道中使用。 + + 用法: + {% with about_content=site_settings|ml:'about_content' %} + {{ site_settings|ml:'site_name' }} + """ + return _ml_value(obj, field_name) diff --git a/templates/core/about.html b/templates/core/about.html index 6898eb9..768aa52 100644 --- a/templates/core/about.html +++ b/templates/core/about.html @@ -9,7 +9,7 @@

{% trans '关于我们' %}

- {% with about_content=site_settings.about_content_zh|default:site_settings.about_content_en %} + {% with about_content=site_settings|ml:'about_content' %} {% if about_content %}
{{ about_content|safe }} @@ -50,7 +50,7 @@
-{% if not site_settings.about_content_zh and not site_settings.about_content_en %} +{% if not site_settings.about_content_zh and not site_settings.about_content_en and not about_content %}
diff --git a/templates/includes/header.html b/templates/includes/header.html index 58f3442..f58c3a7 100644 --- a/templates/includes/header.html +++ b/templates/includes/header.html @@ -31,6 +31,7 @@
{% csrf_token %} +