【问题标题】:Timber how to implement get_current_url wp木材如何实现get_current_url wp
【发布时间】:2020-11-19 23:53:37
【问题描述】:

我已经使用 Wordpress 一年多了。但我坚持使用 Timber twig 框架获取当前 URL。我在代码下面尝试了这些代码,但没有运气。

{{ site.url.current }}
{{ app.request.getRequestUri() }}

Twig templates engine: get current url

【问题讨论】:

    标签: wordpress twig timber


    【解决方案1】:

    你试过了吗:

    URLHelper::get_current_url()
    

    文档:https://timber.github.io/docs/reference/timber-urlhelper/#get_current_url

    因此,您应该能够将其作为变量输入到您的模板中。

    或者,如果您想更进一步并extend Timber's Twig,即创建一个过滤器或函数,例如:

    $twig->addFilter(new \Twig_SimpleFilter('is_current_url', function ($link) {
        return (URLHelper::get_current_url() == $link) ? true : false;
    }));
    

    这应该归结为:

    {{ 'http://example.org/2015/08/my-blog-post' | is_current_url }}
    

    顺便说一句:在内部,get_current_url() 返回:$_SERVER['HTTP_HOST']/$_SERVER['SERVER_NAME'] + $_SERVER["REQUEST_URI"]

    【讨论】:

    • 谢谢,@wp78de 我期待这样的情况。 {% if(URLHelper::get_current_url() == 'example.com/custom/') %} true {% else %} false {% endif %}
    【解决方案2】:

    add_to_context 函数下的 functions.php 中添加 ['current_url'] 对我有用:

        public function add_to_context($context)
    {
        // $context['foo']   = 'bar';
        $context['current_url'] = Timber\URLHelper::get_current_url();
        $context['site']  = $this;
        return $context;
    }
    

    然后你就可以在你的 twig 模板中全局使用它了:

     <pre>
      Current Url:  {{ dump(current_url) }}
    </pre>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-09
      • 1970-01-01
      • 1970-01-01
      • 2017-09-09
      • 1970-01-01
      • 1970-01-01
      • 2014-04-17
      • 2023-01-23
      相关资源
      最近更新 更多