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

后端 未结 9 1248
我寻月下人不归
我寻月下人不归 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?
    

提交回复
热议问题