在js文件中输出一个env值

Output an env value in a js file

我有一个 /.env 文件,其中包含站点的各种环境设置。我有一个 /themes/my-theme/assets/js/app.js 文件,其中包含一些在所有页面上运行的 JS 代码。我想从 app.js 文件本身的 env 文件中输出一个值。明确地说,我想添加一个名为 timeout 的 JS 变量,并为其分配由 .env 文件中的 TIMEOUT 设置指定的值。

关于如何在 10 月 CMS 中执行此操作的任何想法?

首先将 .env 文件添加到 root 并添加您的 variable and value

.env file content

TIMEOUT=3000

Now in your layout's code section add this code

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

Now in your layout's markup section add this code

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

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

如果您遇到任何问题,请发表评论。