fix: 修复关于我们多语言切换和语言切换按钮回退问题
This commit is contained in:
@@ -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 的 <field_name>_zh 或 <field_name>_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)
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
<div class="section-title">
|
||||
<h2>{% trans '关于我们' %}</h2>
|
||||
</div>
|
||||
{% 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 %}
|
||||
<div class="about-content">
|
||||
{{ about_content|safe }}
|
||||
@@ -50,7 +50,7 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{% 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 %}
|
||||
<section class="section">
|
||||
<div class="container">
|
||||
<div class="section-title">
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
</ul>
|
||||
<form action="{% url 'set_language' %}" method="post" class="lang-switcher ms-lg-3 mt-2 mt-lg-0">
|
||||
{% csrf_token %}
|
||||
<input type="hidden" name="next" value="{{ request.get_full_path|force_escape }}">
|
||||
<button type="submit" name="language" value="zh-hans" class="btn btn-sm {% if LANGUAGE_CODE == 'zh-hans' %}btn-primary{% else %}btn-outline-primary{% endif %}">中文</button>
|
||||
<button type="submit" name="language" value="en" class="btn btn-sm {% if LANGUAGE_CODE == 'en' %}btn-primary{% else %}btn-outline-primary{% endif %}">EN</button>
|
||||
</form>
|
||||
|
||||
Reference in New Issue
Block a user