【问题标题】:In Wordpress using a custom Timber/Twig theme how can I fetch .env variables in a twig file?在使用自定义 Timber/Twig 主题的 Wordpress 中,如何在 twig 文件中获取 .env 变量?
【发布时间】:2022-06-17 07:43:39
【问题描述】:

正如标题所说。我有一个使用木材插件的自定义主题,所以它的模板有树枝。但我不确定如何从 env 文件中获取数据以在 twig 文件中使用。

【问题讨论】:

  • 我认为您只是从错误的角度看待问题,您只需要将 env var 从调用 twig->render 函数的 PHP 文件传递​​给 twig 模板 =)跨度>

标签: wordpress environment-variables twig timber


【解决方案1】:

这就是我从 twig 模板全局访问 ENV 变量的方式。

我不确定这是否是一个安全漏洞,但我认为用户无法访问 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();

然后你可以像这样使用它们:

<script>
   window.stripe = Stripe('{{ env['STRIPE_PUBLIC_KEY'] }}');
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 2019-11-03
    • 2020-08-31
    • 1970-01-01
    • 2018-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多