views:

153

answers:

2

Hello,

I'm trying to include some javascript code inside a template.

The code of my html page :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
       "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <script type="text/javascript" src="jquery-1.4.2.min.js"></script>
    <script type="text/javascript" src="jquery-jtemplates.js"></script>
</head>

<body>
    <div id="infos"></div>
    <div id="my_template"></div>

    <script type="text/javascript">
        $(document).ready(function() {
            $('#my_template').setTemplateURL("my_template.html");
            try {
                $('#my_template').processTemplate({'var' : 1});
            }
            catch (e) {
                $('#infos').html('error : '+e);
            }
            $('#my_button').click(function(){
                alert('it works outside');
            });
        });
    </script>

</body>
</html>

and the template

content of the template<br/>
{#if $T.var == 1}

 <script type="text/javascript">
  $(document).ready(function() {

   $('#my_button').click(function(){
    alert('it works inside');
   });

  });
 </script>
 <input type='submit' id='my_button' value='click me' onclick='alert("direct");'/>

{#else}
 not working
{#/if}

produce me an error inside the infos balise

error : SyntaxError: missing } after function body

if I just put alert('it works inside'); inside the script balise (remove all the jquery related code), the page load, the two message "direct" and "it works outside" are showed but not "it works inside" message.

It's suppose to works as said on the doc page

Allow to use JavaScript code in templates

Thank you

A: 

I've found a solution I think.

The template allow me to execute only relly simple JS inside <script> tags but I can either call a function defined in my main page or use an external JS file

content of the template<br/>
{#if $T.var == 1}
    <script type="text/javascript" src="fct_template.js"></script>
    <input type='submit' id='my_button' value='click me'/>
{#else}
    not working
{#/if}

where I can put all the code I want

Martin Trigaux
+1  A: 

Looks like {} signs are garbled by the template preprocessor. I'm not familiar with jtemplate, but this might be the solution for your problem: http://stackoverflow.com/questions/1238449/jtemplates-escape

Tgr
thank you, with the {#literal} tag, it seems to work well
Martin Trigaux