python - Replacing a character in Django template -


i want change & and in page's meta description.

this tried

{% if '&' in dj.name %}     {{ dj.name.replace('&', 'and') }} {% else %}     {{ dj.name }} {% endif %} 

this doesn't work. still shows &

dj.name.replace('&', 'and') can not invoke method arguments.you need write custom filter.

official guide here:

https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/#registering-custom-filters

ok, here example, say, in app named 'questions', want write filter to_and replaces '&' 'and' in string.

in /project_name/questions/templatetags, create blank __init__.py, , to_and.py 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 can enjoy:

{{ string|to_and }} 

note, directory name templatetags , file name to_and.py can not other names.


Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -