AL-zami
AL-zami

Reputation: 9066

javascript in twig template layout yields error

i have a base twig template where i can insert body and js according to my need.Base template is like following :

<!DOCTYPE html>
<html>
<head>
    <title>{{ title }}</title>
    {{ block("stylesheets") }}
</head>
<body>
<div class="container">
    <div align="center">

        {{ block("body") }}

    </div>
</div>
{{ block("javascripts") }}

</body>
</html>

And i have a welcome.html which will use this template.Welcome page has some html and javascript.It renders the html inside it if no js is provided.If i provide any javascript it stops working and i get the following error :

Fatal error: Uncaught exception 'Twig_Error_Syntax' with message 'A block must start with a tag name.' in C:\xampp\htdocs\practice\PHPMVC\Elixir\View\Welcome\welcome.html:14 Stack trace: #0 C:\xampp\htdocs\practice\PHPMVC\vendor\twig\twig\lib\Twig\TokenParser\Block.php(40): Twig_Parser->subparse(Array, true) #1 C:\xampp\htdocs\practice\PHPMVC\vendor\twig\twig\lib\Twig\Parser.php(190): Twig_TokenParser_Block->parse(Object(Twig_Token)) #2 C:\xampp\htdocs\practice\PHPMVC\vendor\twig\twig\lib\Twig\Parser.php(103): Twig_Parser->subparse(NULL, false) #3 C:\xampp\htdocs\practice\PHPMVC\vendor\twig\twig\lib\Twig\Environment.php(692): Twig_Parser->parse(Object(Twig_TokenStream)) #4 C:\xampp\htdocs\practice\PHPMVC\vendor\twig\twig\lib\Twig\Environment.php(750): Twig_Environment->parse(Object(Twig_TokenStream)) #5 C:\xampp\htdocs\practice\PHPMVC\vendor\twig\twig\lib\Twig\Environment.php(447): Twig_Environment->compileSource(Object(Twig_Source)) #6 C:\xampp\htdocs\practice\PHPMVC\vendor\twig\twig\lib\Twig\Environment.php(362): Twig_E in C:\xampp\htdocs\practice\PHPMVC\Elixir\View\Welcome\welcome.html on line 14

Welcome.html :

{ extends "Base/Base.html" }
{ block body }
<ul>
{ for user in users }
    <li>{{ user.name}} is {{ user.age }} years old !</li>
{ endfor }
</ul>
<input type = 'button' value = 'mybtn' id = 'btn'>

{ endblock body }

{ block javascripts }
<script type="text/javascript">
 document.getElementById('btn').addEventListener('click',function(){

 })

</script>
{ endblock javascripts }

i have used lexer to rewrite syntax rule like following :

$lexer = new \Twig_Lexer($twig,array(
                         'tag_block'    =>array('{','}'),
                         'tag_variable' =>array('{{','}}')
));

Upvotes: 0

Views: 1314

Answers (1)

john Smith
john Smith

Reputation: 17906

your lexxer rewrite will match your js as twig tag block

the brackets of that js object:

function(){}  

you could make use of the varbatim tag

{ block javascripts }
{ verbatim }
<script type="text/javascript">
 document.getElementById('btn').addEventListener('click',function(){

 })

</script>
{ endverbatim }
{ endblock javascripts }

the content between verbatim will not be parsed by twig

https://twig.sensiolabs.org/doc/2.x/tags/verbatim.html

Upvotes: 2

Related Questions