javajavascriptgoogle-closure

How to properly use javascript in closure soy files?


I just joined a team that uses google-closure in java to build it's site output from soyfiles. This works well for html but at the moment it's quite ugly for javascript. The current approach is to surround the javascript in {literal}, which means we get none of the benefits. An example of what we are doing is below:

{namespace forms autoescape="contextual"}
{template myForm}
//.... stuff happens

{call js.myFormJs data="$someParam" /}

js:

{namespace forms autoescape="contextual"}
/**
 * @param foo
 */
{template myForm}
<script type="text/javascript">
{literal}

//js stuff happens

var myVariable {/literal}{$foo}{literal};

//js stuff happens

{/literal}
</script>
{/template}

We also use in some places soy params in {if} blocks to determine if entire parts of the script are generated. As shown above, these js soy files are almost always called as part of some other siy file with is usually all html.

So my question is, what should we be doing? I looked at the |escapeJs flag but I cant find where to apply it. Getting rid of {literal} will cause rendering errors an all the javascript braces. Is there a better way to do this? Should I be using soy files at all for js (as I am beginning to suspect we shouldn't)?


Solution

  • so there are a few approaches here, the best approach is to generate your javascript outside the template. you could also replace your curly braces with {lb} and {rb}'s but that makes the code nigh unreadable I am sure.