ashwnacharya
ashwnacharya

Reputation: 14871

Escaping strings in JTemplate

I have a JTemplate string that looks like this

<a class="add"  href="#" onclick="javascript:myfunction('{$T.Properties.Title}')" >

This code breaks when my parameter $T.Properties.Title is a string which contains a single quote character in it.

I could use a double quote character while passing my parameter value, but my code will then break for double quotes.

How do I escape the input string so that my code works for strings that have both single and double quotes in them?

Upvotes: 1

Views: 406

Answers (2)

Dilip Rajkumar
Dilip Rajkumar

Reputation: 7074

I had the same problem, finally what I did was escaped the quotes in java script.

Following is my code.

In Template:

$('#content').setParam('getUrl', getUrl);

In HTML; inside template.

href="{$P.getUrl($T.RESULTS.URL)}"

JS Method:

function(theLink){
  return theLink.replace(/\"/g, "%22");

  //If you want to escape all the characters use the following
  return escape((theLink))
}

Cheers..:)

Upvotes: 0

jfrej
jfrej

Reputation: 4648

You need to escape quotes with backslashes when you create the object:

Properties = {Title: 'I\'m lovin\' my quotes'};

EDIT :

As per your comment:

No control over the source, sadly. :( the JSON comes from a third party site

You can either try using setTemplate(s, [], {filter_params: true});

which according to the docs is using escapeHTML - but I haven't tried and I'm not sure how it works.

See this question about escaping HTML with filter_data: jtemplates-html-in-variables

Or try escaping quotes after you receive the JSON object. I believe in PHP you can use json_encode - see here: json-parse-error-with-double-quotes

Other solutions described here: javascript-how-escape-quotes-in-a-var-to-pass-data-through-json

Upvotes: 0

Related Questions