Reputation: 97
I have two flag icons and I am willing to give them URLs to determine which language should be displayed using Django translation. Though, I am kind of confused about this. How may I do such a thing? To be more specific, when the client clicks on Iran's flag, the language prefix in the URL should be changed to 'fa-ir' (www.domain.com/fa-ir/products)
HTML:
<ul class="navbar-nav d-block d-lg-none ml-auto mr-3">
<li class="nav-item">
<a href="{% url 'products'%}"><div class="ukflag mr-1"></div></a>
<a href="fa-ir/{% url 'products' %}"><div class="irflag"></div></a>
</li>
</ul>
Products.Views.py:
from django.shortcuts import render
from django.views.generic import TemplateView
class ProductPageView(TemplateView):
template_name = 'products.html'
URLs.py:
from django.contrib import admin
from django.urls import include, path
from home.views import HomePageView
from products.views import ProductPageView
from django.conf.urls.i18n import i18n_patterns
from django.utils.translation import gettext_lazy as _
urlpatterns = i18n_patterns(
path(_('admin/'), admin.site.urls),
path("", HomePageView.as_view(), name='home'),
path(_('products/'), ProductPageView.as_view(), name='products'),
prefix_default_language = False
)
Upvotes: 1
Views: 357
Reputation: 12849
If you wanted to provide a language selector you could do something like this;
{% load i18n %}
{% get_available_languages as languages %}
<form action="{% url "set_language" %}" method="post">
{% csrf_token %}
<div class="form-group">
<select name="language" class="form-control" onchange="this.form.submit()">
{% for language in languages %}
<option value="{{ language.code }}"
{% if language.code == LANGUAGE_CODE %}selected="selected"{% endif %}>
{{ language.name_local }}
</option>
{% endfor %}
</select>
</div>
</form>
{% endif %}
When you select a choice & the request hits that set_language
view the system will activate the chosen language. Then when you view a page you'll see things like links prefixed with the current language.
Then to take that logic & apply it to your markup, maybe you could use the language code to set your flags?
<ul class="navbar-nav d-block d-lg-none ml-auto mr-3">
{% for language in languages %}
<li class="nav-item">
<a href="{% url 'products'%}"><div class="{{language.code}}flag mr-1"></div></a>
</li>
{% endfor %}
</ul>
The links in the form will point at the activated language, e.g. /en/products/
. This is why, in a language selector you wouldn't use i18n
to display the choices, because you want them to be specific to a speaker of that language & not translated into the current language.
Upvotes: 1