在HTML中,如果满足条件,可以向Django的URL中添加语言代码。

huangapple go评论50阅读模式
英文:

Django add language code to url in html if condition

问题

{% if '/{{LANGUAGE_CODE}}/accounts/dashboard/' == request.path %} active {% endif %}

英文:

I have a navbar that shows active when it is in the current section. I have internationalised the web so now the url includes the language code. How can I add the language code in the if condition below?

{% if '/{LANGUAGE_CODE}/accounts/dashboard/' == request.path %} active {% endif %}

webpage url: http://127.0.0.1:8000/en/accounts/dashboard

{% load i18n %}
{% get_current_language as LANGUAGE_CODE %}

<aside class="col-md-3">
  <!--   SIDEBAR   -->
  <ul class="list-group">
    <a class="list-group-item {% if '/{LANGUAGE_CODE}/accounts/dashboard/' == request.path %} active {% endif %}" href="{% url 'dashboard' %}"> Dashboard </a>
[continues...]

I tried {{LANGUAGE_CODE}} and some pasting. Any ideas how to get the if condition working?

答案1

得分: 1

你可以使用 add 过滤器来连接你的字符串,并使用 with 标签来缓存这个复杂的变量。结果会如下所示:

{% load i18n %}
{% get_current_language as LANGUAGE_CODE %}

<aside class="col-md-3">
  <!--   SIDEBAR   -->
  <ul class="list-group">
    {% with "/"|add:LANGUAGE_CODE|add:"/accounts/dashboard/" as dashboard_url %}
    <a class="list-group-item {% if dashboard_url == request.path %} active {% endif %}" href="{% url 'dashboard' %}"> Dashboard </a>
    {% endwith %}
    [继续...]
英文:

You can use add filter to concatenate your strings and with tag to cache this complex variable. The result would look like this:

{% load i18n %}
{% get_current_language as LANGUAGE_CODE %}

&lt;aside class=&quot;col-md-3&quot;&gt;
  &lt;!--   SIDEBAR   --&gt;
  &lt;ul class=&quot;list-group&quot;&gt;
    {% with &quot;/&quot;|add:LANGUAGE_CODE|add:&quot;/accounts/dashboard/&quot; as dashboard_url %}
    &lt;a class=&quot;list-group-item {% if dashboard_url == request.path %} active {% endif %}&quot; href=&quot;{% url &#39;dashboard&#39; %}&quot;&gt; Dashboard &lt;/a&gt;
    {% endwith %}
[continues...]

huangapple
  • 本文由 发表于 2023年2月16日 03:29:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75464606.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定