【发布时间】:2020-11-19 23:53:37
【问题描述】:
我已经使用 Wordpress 一年多了。但我坚持使用 Timber twig 框架获取当前 URL。我在代码下面尝试了这些代码,但没有运气。
{{ site.url.current }}
{{ app.request.getRequestUri() }}
【问题讨论】:
我已经使用 Wordpress 一年多了。但我坚持使用 Timber twig 框架获取当前 URL。我在代码下面尝试了这些代码,但没有运气。
{{ site.url.current }}
{{ app.request.getRequestUri() }}
【问题讨论】:
你试过了吗:
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"]
【讨论】:
在 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>
【讨论】: