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

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

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

  1. {% load i18n %}
  2. {% get_current_language as LANGUAGE_CODE %}
  3. <aside class="col-md-3">
  4. <!-- SIDEBAR -->
  5. <ul class="list-group">
  6. <a class="list-group-item {% if '/{LANGUAGE_CODE}/accounts/dashboard/' == request.path %} active {% endif %}" href="{% url 'dashboard' %}"> Dashboard </a>
  7. [continues...]

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

答案1

得分: 1

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

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

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

  1. {% load i18n %}
  2. {% get_current_language as LANGUAGE_CODE %}
  3. &lt;aside class=&quot;col-md-3&quot;&gt;
  4. &lt;!-- SIDEBAR --&gt;
  5. &lt;ul class=&quot;list-group&quot;&gt;
  6. {% with &quot;/&quot;|add:LANGUAGE_CODE|add:&quot;/accounts/dashboard/&quot; as dashboard_url %}
  7. &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;
  8. {% endwith %}
  9. [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:

确定