How to set a value of a variable inside a template code?

后端 未结 9 1081
我寻月下人不归
我寻月下人不归 2020-11-27 09:55

Say I have a template


Hello {{name}}!

While testing it, it would be useful to define the

相关标签:
9条回答
  • 2020-11-27 10:32

    Create a template tag:

    The app should contain a templatetags directory, at the same level as models.py, views.py, etc. If this doesn’t already exist, create it - don’t forget the __init__.py file to ensure the directory is treated as a Python package.

    Create a file named define_action.py inside of the templatetags directory with the following code:

    from django import template
    register = template.Library()
    
    @register.simple_tag
    def define(val=None):
      return val
    

    Note: Development server won’t automatically restart. After adding the templatetags module, you will need to restart your server before you can use the tags or filters in templates.


    Then in your template you can assign values to the context like this:

    {% load define_action %}
    {% if item %}
    
       {% define "Edit" as action %}
    
    {% else %}
    
       {% define "Create" as action %}
    
    {% endif %}
    
    
    Would you like to {{action}} this item?
    
    0 讨论(0)
  • 2020-11-27 10:32

    There are tricks like the one described by John; however, Django's template language by design does not support setting a variable (see the "Philosophy" box in Django documentation for templates).
    Because of this, the recommended way to change any variable is via touching the Python code.

    0 讨论(0)
  • 2020-11-27 10:32

    Perhaps the default template filter wasn't an option back in 2009...

    <html>
    <div>Hello {{name|default:"World"}}!</div>
    </html>
    
    0 讨论(0)
提交回复
热议问题