0

I need to change any ' to \' when displaying a value in my template.

so eg {{ account.company_name|escapejs }} should replace any ' with \'

how do I do that ?

thanks Thomas

** UPDATED CODE BASED ON COMMENTS BELOW **

My directory-structure is like this:

myapp/
  ....
  templatetags/
     __init__.py
     replace.py

Replace.py contains:

from django import template
register = template.Library()
from django.template import defaultfilters

@register.filter
@defaultfilters.stringfilter
def replace(value, args=","):
    try:
        old, new = args.split(',')
        return value.replace(old, new)
    except ValueError:
        return value

and in settings.py I have

INSTALLED_APPS = ( 'myapp' )

In my template I try to load the customtag like this:

{% from replace load replace %}

and it is used like this

company_name='{{ account.company_name|escapejs|replace:"',\'" }}'

I then received this error:

TemplateSyntaxError: Invalid block tag: 'from'

and then changed to

{% load replace %} instead of {% from replace load replace %}

but then I get this error:

TemplateSyntaxError: 'replace' is not a valid tag library: Template library replace not found, tried google.appengine._internal.django.templatetags.replace

Any help is appreciated

2 Answers 2

1

Use the addslashes built-in filter:

From the documentation's example:

{{ value|addslashes }}

If value is "I'm using Django", the output will be "I\'m using Django".

Sign up to request clarification or add additional context in comments.

Comments

0

You can write your own filter:

@register.filter
@defaultfilters.stringfilter
def replace(value, args=","):
    try:
        old, new = args.split(',')
        return value.replace(old, new)
    except ValueError:
        return value

Then in your template:

{% load replace from mycustomtags %}

{{ account.company_name|escapejs|replace:"',\'" }}

(I haven't tested)

8 Comments

thanks, Where do I add the filter ? Sorry if this is a basic question
and added it to my template, per your instructions, but I cannot get it to work. I am getting this error "TemplateSyntaxError: 'replace' is not a valid tag library: Template library replace not found, tried google.appengine._internal.django.templatetags.replace"
Add from django.template import default filters. Sorry that I missed that.
I am getting this error "TemplateSyntaxError: 'replace' is not a valid tag library: Template library replace not found, tried google.appengine._internal.django.templatetags.replace" I tried both {% load replace %} and {% load replace from mycustomtags %} at the top top of my template
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.