本文介紹 django.conf.urls.i18n.i18n_patterns
的用法。
聲明
i18n_patterns(*urls, prefix_default_language=True)
該函數可以在根 URLconf 中使用,Django 會自動將當前活動語言代碼添加到
中定義的所有 URL 模式。i18n_patterns()
將 prefix_default_language
設置為 False
會從默認語言 (
) 中刪除前綴。這在將翻譯添加到現有站點時很有用,這樣當前的 URL 就不會改變。LANGUAGE_CODE
示例 URL 模式:
from django.conf.urls.i18n import i18n_patterns
from django.urls import include, path
from about import views as about_views
from news import views as news_views
from sitemap.views import sitemap
urlpatterns = [
path('sitemap.xml', sitemap, name='sitemap-xml'),
]
news_patterns = ([
path('', news_views.index, name='index'),
path('category/<slug:slug>/', news_views.category, name='category'),
path('<slug:slug>/', news_views.details, name='detail'),
], 'news')
urlpatterns += i18n_patterns(
path('about/', about_views.main, name='about'),
path('news/', include(news_patterns, namespace='news')),
)
在定義了這些 URL 模式之後,Django 會自動將語言前綴添加到由i18n_patterns
函數添加的 URL 模式中。例子:
>>> from django.urls import reverse
>>> from django.utils.translation import activate
>>> activate('en')
>>> reverse('sitemap-xml')
'/sitemap.xml'
>>> reverse('news:index')
'/en/news/'
>>> activate('nl')
>>> reverse('news:detail', kwargs={'slug': 'news-slug'})
'/nl/news/news-slug/'
使用 prefix_default_language=False
和 LANGUAGE_CODE='en'
,URL 將是:
>>> activate('en')
>>> reverse('news:index')
'/news/'
>>> activate('nl')
>>> reverse('news:index')
'/nl/news/'
警告
僅允許在根 URLconf 中使用。在包含的 URLconf 中使用它會引發 i18n_patterns()
異常。ImproperlyConfigured
警告
確保您沒有可能與 automatically-added 語言前綴衝突的非前綴 URL 模式。
相關用法
- Python import__用法及代碼示例
- Python itertools.takewhile用法及代碼示例
- Python id()用法及代碼示例
- Python ipaddress.collapse_addresses用法及代碼示例
- Python ipaddress.IPv4Address.reverse_pointer用法及代碼示例
- Python io.text_encoding用法及代碼示例
- Python string isidentifier()用法及代碼示例
- Python numpy irr用法及代碼示例
- Python ipaddress.IPv4Address.__format__用法及代碼示例
- Python calendar isleap()用法及代碼示例
- Python math isclose()用法及代碼示例
- Python string isupper()用法及代碼示例
- Python itertools.cycle用法及代碼示例
- Python itertools.dropwhile用法及代碼示例
- Python scipy integrate.trapz用法及代碼示例
- Python itertools.repeat用法及代碼示例
- Python ipaddress.IPv4Network.supernet用法及代碼示例
- Python string isalnum()用法及代碼示例
- Python inspect.Parameter.replace用法及代碼示例
- Python numpy matrix identity()用法及代碼示例
- Python inspect.Parameter.kind用法及代碼示例
- Python int轉exponential用法及代碼示例
- Python ipaddress.IPv4Network.supernet_of用法及代碼示例
- Python itertools.combinations_with_replacement用法及代碼示例
- Python itertools.groupby()用法及代碼示例
注:本文由純淨天空篩選整理自djangoproject.com大神的英文原創作品 django.conf.urls.i18n.i18n_patterns。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。