Output An Env Value In A Js File

- 1 answer

I have a /.env file containing various environment settings for the site. I have a /themes/my-theme/assets/js/app.js file containing some JS code that runs on all pages. I want to output a value from the env file in the app.js file itself. To be clear I want to add a JS variable called timeout and assign it the value specified by the TIMEOUT setting in the .env file.

Any ideas on how to do this in October CMS?



First add .env file to root and add your variable and value

.env file content


Now in your layout's code section add this code

function onStart()
    $this['env_timeout'] = env('TIMEOUT', '2000');
    // -----------  env var name - ^       ^ - default value    

enter image description here

Now in your layout's markup section add this code

<script>var env_timeour = {{env_timeout}};</script>

enter image description here

Now you can use it anywhere in your js just make sure you add this scriptbefore your js file so variable available to your js file

enter image description here

If you face any issue please comment.