Question

I use JavaScript-code in a velocity-template and it's not working!

I read content with this template and want to set this to a js-variable, but there are line-breaks in the content and I get the following error:

SyntaxError: unterminated string literal

In the rendered code there you see the error:

var exampleText = 'This is the first line

and this is the second line.';

In the original code it is written this way:

    var exampleText = '$question.answer.data';
var regularPanels = new A.Panel( { 
    bodyContent: exampleText, 
    collapsible: true, 
    collapsed: true,
    headerContent: '$question.data' } ) .render('#regularPanels$counter$reserved-article-id.data$randomNamespace');  

});

Is there a possibility to ignore the linebreak for the js-compilation, but still show it on the complete rendered page?


Okay, I solved it with the help of the EscapeTool by Velocity.

Combined with the answer from emiliocai it's the following code which works fine:

<div id="example-text" style="display:none;">
   <p>$escapeTool.java($question.answer.data).replace("\n","<br />")</p>
</div>

<script type="text/javascript" charset="utf-8">

AUI().ready('aui-panel', function(A) { 

var exampleText = document.getElementById('example-text').innerHTML;
var regularPanels = new A.Panel( { 
    bodyContent: exampleText, 
    collapsible: true, 
    collapsed: true,
    headerContent: '$question.data' } ) .render('#regularPanels$counter$reserved-article-id.data$randomNamespace');  

});

</script>

It might be, that it would work without the hidden <div>-Tag, but I haven't tested it yet.

So also possible would be:

var exampleText = '$escapeTool.java($question.answer.data).replace("\n","<br />")';

Tested it -> works!

Was it helpful?

Solution

I'm sorry but newlines are not acceptable in JavaScript, not sure how your template looks like but if you really cannot replace the newlines by \n or <br> the you can do a trick:

  • In the template render the contents coming from the database into a hidden div:

    <div id="example-text" style="display:none">$question.answer.data</div>

  • In your javascript code read the contents of the div into your variable:

    var exampleText = document.getElementById('example-text').innerHTML;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top