Assign Value of Named URL to a Variable in Django Templates

后端 未结 2 1687
刺人心
刺人心 2021-02-18 23:38

In my Django template I need to assign the value of a names url into a variable within a with block so I can use it in multiple places.

I need to achieve something like

相关标签:
2条回答
  • 2021-02-18 23:58

    I think you'll have to either create your own template tag to manage this problem or create the necessary data in the view and pass it in to the template.

    Depending on exactly what you're trying to do maybe including another template and sending in your defined variable could do it, but I doubt it.

    The thinking behind Djangos templating system is to make it so there isn't very much logic in the templates. And thus it's back to either preparing the data you need for output in the view or making a template tag.

    0 讨论(0)
  • 2021-02-19 00:04

    Why create a new template tag/filter if the feature is in core?

    Look the samples at: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#url

    {% url 'path.to.view' arg arg2 as the_url %}
    
    <a href="{{ the_url }}">I'm linking to {{ the_url }}</a>
    

    and

    {% url 'path.to.view' as the_url %}
    {% if the_url %}
      <a href="{{ the_url }}">Link to optional stuff</a>
    {% endif %}
    
    0 讨论(0)
提交回复
热议问题