Ad

Access Twig Variable In OctoberCMS Javascript File

- 1 answer

I am Using OctoberCMS which is based in Laravel Framework and I set variable in my html file {% set name = 'Juan' %} and i am trying to access it in my Javascript file by setting variable like this var myName = '{{ name }}' and i alert the variable myName but unfortunately it doesn't display the variable myName instead it displayed the whole string like this {{ name }}

Ad

Answer

The problem is you are defining whole thing in javascript

So, template engine has no clue what you want, what I suggest is just define variables in Html like this

so previously you did this.

{% set name = 'Juan' %}

so now to pass this variable to js you can do something like this for simplicity. [its unprofessional and I do not suggest it instead we can use our namespace/object and pass it]

<script>var myName = '{{ name }}';</script>

make sure this line is not written in js file it must be in one of .htmlayout/template or in markup section.

then throughout in your project inside js you can access it.

alert(myName);

and if it do not seems relevant to you then we suggest you to post laravel code which can do stuff like this so we give better working relevant solution.

if you find any doubts please comment.

Ad
source: stackoverflow.com
Ad