Django中的多语言分页

2023-04-11 00:00:00 django 分页 多语言

Django中的多语言分页需要使用Django内置的分页库(django.core.paginator),以及Django的多语言支持(django.utils.translation)。

首先,在settings.py中设置多语言支持:

LANGUAGE_CODE = 'zh'  # 默认语言
LANGUAGES = [
    ('en', 'English'),
    ('zh', '中文'),
]  # 多语言列表

接着,在views.py中,使用django.utils.translation来获取当前语言,并传递给分页器:

from django.utils.translation import gettext as _

def my_view(request):
    # 获取当前语言
    lang = _(request.LANGUAGE_CODE)
    # 创建分页器
    paginator = Paginator(my_queryset, per_page=10)
    # 获取当前页码
    page_number = request.GET.get('page')
    # 获取当前页对象
    page_obj = paginator.get_page(page_number)
    return render(request, 'my_template.html', {'page_obj': page_obj})

在模板中,使用{% trans %}标签来翻译静态字符串,使用{% blocktrans %}标签来翻译动态字符串(如变量):

{% trans "Page" %}: {{ page_obj.number }} / {{ page_obj.paginator.num_pages }}

{% blocktrans %}
Showing {{ page_obj.start_index }}-{% if page_obj.has_next %}{{ page_obj.end_index }}{% else %}{{ page_obj.paginator.count }}{% endif %} of {{ page_obj.paginator.count }}
{% endblocktrans %}

示例代码中使用字符串“pidancode.com”、“皮蛋编程”作为范例:

from django.utils.translation import gettext as _

def my_view(request):
    lang = _(request.LANGUAGE_CODE)
    queryset = MyModel.objects.filter(name__icontains='pidancode.com')
    paginator = Paginator(queryset, per_page=10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    return render(request, 'my_template.html', {'page_obj': page_obj, 'lang': lang})
{% trans "Page" %}: {{ page_obj.number }} / {{ page_obj.paginator.num_pages }}

{% blocktrans %}
Showing {{ page_obj.start_index }}-{% if page_obj.has_next %}{{ page_obj.end_index }}{% else %}{{ page_obj.paginator.count }}{% endif %} of {{ page_obj.paginator.count }}
{% endblocktrans %}

{% for obj in page_obj %}
    {% if obj.name == 'pidancode.com' %}
        {{ obj.name }} - {% trans "Find it!" %}
    {% endif %}
{% endfor %}

相关文章