[英]In Wordpress using a custom Timber/Twig theme how can I fetch .env variables in a twig file?
As the title says.正如标题所说。 I have a custom theme that is using timber plugin so has twig for its templates.
我有一个使用木材插件的自定义主题,所以它的模板有 twig。 But I am not sure how to fetch data from the env file to use in a twig file.
但我不确定如何从 env 文件中获取数据以在 twig 文件中使用。
This is how I would globally access the ENV variables from twig templates.这就是我从 twig 模板全局访问 ENV 变量的方式。
I'm not sure if this would be a security flaw but I don't think a user can access the twig context (someone correct me if I'm wrong).我不确定这是否是一个安全漏洞,但我认为用户无法访问 twig 上下文(如果我错了,请有人纠正我)。
<?php
class Site extends TimberSite {
function __construct() {
/**
* Load composer dependencies
*/
$composer_autoload = __DIR__ . '/vendor/autoload.php';
if ( file_exists( $composer_autoload ) ) require_once $composer_autoload;
/**
* Load global ENV variables
*/
$dotenv = Dotenv\Dotenv::createImmutable( ABSPATH . '/..' );
$dotenv->load();
add_filter( 'timber_context', [ $this, 'add_to_context' ] );
parent::__construct();
}
function add_to_context( $context ) {
/**
* Load environment variables in twig
*/
$context['env'] = $_ENV;
return $context;
}
}
new Site();
You could then use them like so:然后你可以像这样使用它们:
<script>
window.stripe = Stripe('{{ env['STRIPE_PUBLIC_KEY'] }}');
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.