Replacing a character in Django template

后端 未结 2 1882
慢半拍i
慢半拍i 2021-01-01 20:54

I want to change & to and in the my page\'s meta description.

This is what I tried

{% if \'&\' in dj.name %}
           


        
2条回答
  •  时光说笑
    2021-01-01 21:33

    dj.name.replace('&', 'and') You can not invoke method with arguments.You need to write a custom filter.

    Official guide is here:

    https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

    Ok, here is my example, say, in an app named 'questions', I want to write a filter to_and which replaces '&' to 'and' in a string.

    In /project_name/questions/templatetags, create a blank __init__.py, and to_and.py which goes like:

    from django import template
    
    register = template.Library()
    
    @register.filter
    def to_and(value):
        return value.replace("&","and")
    

    In template , use:

    {% load to_and %}
    

    then you can enjoy:

    {{ string|to_and }}
    

    Note, the directory name templatetags and file name to_and.py can not be other names.

提交回复
热议问题