Bouke
Bouke

Reputation: 12198

How to link to language's homepage for untranslated page in django-cms?

Within django-cms I have two languages, with one page in Dutch currently not translated into English. When viewing this page, language_chooser does not provide a link for the English translation (as there is not). However, I would like to link the link to the English translation to link to the homepage (or some other English page if it makes sense). Now I could create the needed template tag myself, or some template trickery, but I think this problem has been solved before. Sadly though, I could not find any example of such a solution.

Language chooser is used like this:

<p><small>Choose your language: {% language_chooser %}</small></p>

The default template used by this template tag (source on github):

{% load menu_tags %}
{% for language in languages %}
<a href="{% page_language_url language.0 %}"{% ifequal current_language language.0 %} class="current"{% endifequal %}>{{ language.1 }}</a>
{% endfor %}

Rendered html (note the empty href for link to English):

<p><small>Choose your language: 
<a href="">English</a>
<a href="/nl/contact/" class="current">Nederlands</a>
</small></p>

Upvotes: 4

Views: 1360

Answers (1)

ojii
ojii

Reputation: 4781

I suggest the following:

Make an own template tag for page_language_url by subclassing it's existing tag, put it in a template tag file in one of your projects apps, let's call it menu_extra_tags.py:

from django import template
from menus.templatetags.menu_tags import PageLanguageUrl
from classytags.arguments import Argument
from classytags.core import Options

register = template.Library()

class PageLanguageUrlAsVariable(PageLanguageUrl):
    name = 'page_language_url_as_variable'
    options = Options(
        Argument('lang'),
        'as',
        Argument('varname', resolve=False),
    )
    def render_tag(self, context, **kwargs):
        varname = kwargs.pop('varname')
        url = super(PageLanguageUrlAsVariable, self).render_tag(context, **kwargs)
        context[varname] = url
        return ''
register.tag(PageLanguageUrlAsVariable)

Now in your language chooser template do:

{% load menu_tags menu_extra_tags %}
{% for language in languages %}
    {% page_language_url_as_variable language.0 as pageurl %}
        <a href="{% if pageurl %}{{ pageurl }}{% else %}/{{ language.0 }}/{% endif %}"{% ifequal current_language language.0 %} class="current"{% endifequal %}>{{ language.1 }}</a>
{% endfor %}

That will redirect you to /en/ (the home page in English) if the English translation for this page is not available.

Upvotes: 6

Related Questions