this is my controller that i pass data to view: here i pass variable named name:
class IndexController extends ControllerBase
{
public function indexAction()
{
$this->assets->addJs('js/script.js');
$this->view->setVar('name', 'john');
}
}
in my volt file i can use name variable and for example creating heading tag like {{name}}
and that s fine but one thing that i want is that i want to pass name variable to a js function . while i pass data to from volt to my script . value of name variable in my js file is undefined
. how can i do that??
<div class="form-group d-flex justify-content-center">
<h1 style="color:red;">{{ name }}</h1> //it works
<button onclick="changeLevel(1, 2,{{ name }})" type="submit" class="btn btn-block rounded buttonStyle " id="SendPhone" disabled>تایید شماره</button>
</div>
You are on the right track, but you have to think a little bit further.
At this moment you have the following code:
<button onclick="changeLevel(1, 2,{{ name }})>Click</button>
When running this code through twig
you get the following output:
<button onclick="changeLevel(1, 2, john)>Click</button>
This means, you will pass the variable john
to the function changeLevel
, but john
is not a known variable in javascript.
So what you actually want to do is to pass the literal string john
, you can achieve this by enquoting the output, e.g.
<button onclick="changeLevel(1, 2,'{{ name }}')>Click</button>