簡體   English   中英

將變量傳遞給 href django 模板

[英]Passing variable to href django template

我有一些問題,也許我可以在下面給出我想要實現的兩個視圖的示例。

class SomeViewOne(TemplateView):
    model = None
    template_name = 'app/template1.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # The downloads view contains a list of countries eg France, Poland, Germany
        # This returns to context and lists these countries in template1
  
class ItemDetail(TemplateView):
    model = None
    template_name = 'app/template2.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        countries_name = kwargs.get('str')
        The view should get the passed "x" with the name of the country where I described it 
        below.


然后在頁面上我有這些國家的列表。 單擊所選國家/地區后,應打開一個新選項卡並顯示所選國家/地區的城市列表。

所以我在循環中使用 template1.html 如下

{% for x in list_countries %}
    <li>
      <a href="{% url 'some-name-url' '{{x}}' %}" class="target='_blank'">{{ x }}</a><br>
    </li>
{% endfor %}

我不能這樣傳遞“x”。 為什么?

下一個視圖的 url 如下所示

path('some/countries/<str:x>/',views.ItemDetail.as_view(), name='some-name-url'),

而且我無法在 href 的模板中給出“x”

如果 Manoj 的解決方案不起作用,請嘗試刪除單引號和 {{ }}。 在我的程序中,我的 integer 不需要用 {{ }} 包裹,所以您的字符串可能也不需要。 我的代碼中有這個:

{% for item in items %}

        <div class="item-title">
          {{ item }}<br>
        </div>
        <a href="{% url 'core:edit_item' item.id %}">Edit {{ item }}</a>
{% endfor %}

它工作得很好。 嘗試:

<a href="{% url 'some-name-url' x %}" class="target='_blank'">{{ x }}</a>

有幾個錯誤,例如:

  1. 它應該只是 url 標簽中的x ,既不是{{x}}也不是'{{x}}'

  2. 您已在 url 參數( some/countries/<str:x>/ )中將值作為x傳遞並使用kwargs.get('str')訪問它,這是不正確的,它應該是kwargs.get('x')

  3. 此外,您沒有在上下文中包含變量countries_name ,甚至沒有返回上下文。

注意:假設您已經在template1.html模板中獲得一些公司,這就是您運行循環的原因。

試試下面的代碼:

視圖.py

class ItemDetail(TemplateView):
    template_name = 'template2.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['countries_name'] = self.kwargs.get('x')
        return context

Template1.html文件

{% for x in list_countries %}
    <li>
      <a onclick="window.open('{% url 'some-name-url' x %}', '_blank')" style='cursor:pointer;'>{{ x }}</a><br>
    </li>
{% endfor %}

然后你可以在模板2.html中從template1.html 1.html傳遞的這個countries_name值。

模板2.html

<p>The clicked country is {{countries_name}}</p>

您不需要用單引號傳遞該變量。

<a href="{% url 'some-name-url' {{ x }} %}" #Just removed single quotes from variable x.

看看它是否顯示在模板上

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM