views:

53

answers:

2

I am looking to create a variable that is a template for repatative elements of my site. I however am only using it infrequently so I do not wish to use a javascript templating engine or library.

I am using jquery... if that effects anyones approach.

This is one of my templates.

$html_template = json_encode("
var html = '<a href=\"javascript:ajax(\'#content\',\'{$conf['dir']['web_url']}profile.php?user_id='+data.id+'\');\">
<div id=\"'+data.id+'\" class=\"fb_user\">
    <img alt=\"'+data.name+'\" height=\"50\" width=\"50\" />
    <p>
        '+data.first_name+'
        <br/>
        '+data.last_name+'
    </p>
</div>';");

I have gotten so lost in escaping I can't work out where I have gone wrong. The plan is to use eval within the templating function to replace the variables.

Hope someone can help

A: 

http://ejohn.org/blog/javascript-micro-templating/

Julian Aubourg
This really doesn't qualify as an answer, it should be a comment unless you're going to provide more information or insight.
Nick Craver
I doubt I can be much clearer than John himself. I am pretty much against re-phrasing what's already been phrased prefectly. The article features a one-function self-contained templating system (no external lib needed) and ways to include templates in HTML docs with no escaping madness. Pretty much answers the OP, don't you think?
Julian Aubourg
A: 
  1. Use an editor with good highlighting and you will see where to escape.
  2. The apostrophes (') that are inside the javascript code shouldn't be escaped, use double backslash (\) instead, so the javascript will see a single backslash and therefore will escape the apostrophe.
  3. In the anchor don't use javascript code as href, use "#" for link and add onClick="...".
  4. I don't think "ajax" is a jQuery function, perhaps you meant "$.ajax", but it has different parameters, may be you should read its manual.
  5. Try to implement it in pure html and js before writing it in php and you'll know where to escape (after it works in first place).
0xAF
Thanks for your input. With regards to the ajax function that is a js function of mine... :D
Pablo