php - 是否可以链接到 Timber 模板中的其他静态页面?
问题描述
目前,要链接到“常见问题”页面,我有以下内容:
Check out our <a href="{{ site.link }}/faq">FAQ</a> page.
但是,我希望能够链接到我的 WordPress 主题中的其他内部页面,而无需在其后手动写入 URL 参数。就像是:
Check out our <a href="{{ site.link('faq') }}">FAQ</a> page.
这在木材中是不可能的吗?我已经检查了文档,但没有看到任何对它的引用,但我觉得我一定遗漏了一些东西。
解决方案
Wordpress 有两个函数可以解决它:get_page_by_path()和get_permalink()
get_page_by_path('page-slug');
get_permalink(page_id);
使用 Timber,您可以编写类似这样的调用 Timber 函数:
{{ function('get_permalink', function('get_page_by_path', 'page-slug')) }}
但可以肯定的是,您应该定义一个 wp 函数以使其不疯狂。您可以使用 functions.php 文件向 WordPress 添加功能,即使您应该定义一个类来扩展 Timber(如果没有,请复制并粘贴它)
class StarterSite extends Timber\Site {
public function __construct() {
add_filter( 'timber/twig', array( $this, 'add_to_twig' ) );
add_filter( 'timber/context', array( $this, 'add_to_context' ) );
$this->add_routes();
parent::__construct();
}
public function add_to_context( $context ) {
$context['menu'] = new Timber\Menu();
$context['site'] = $this;
return $context;
}
public function add_to_twig( $twig ) {
$twig->addFunction( new Timber\Twig_Function( 'get_permalink_by_slug', function($slug) {
return get_permalink( get_page_by_path($slug) );
} ) );
return $twig;
}
}
new StarterSite();
如您所见,我定义了一个名为 get_page_by_slug 的 Twig 函数,它接收带有页面 slug 的字符串。现在,您可以将其写在您的模板上:
{{ get_permalink_by_slug('page-slug') }}
享受 :)
推荐阅读
- android - TextView 的文字没有变化
- c# - IValueConverter 计算 TextBlock 的新大小
- javascript - 使用动画时,clearInterval 不会停止触发事件,或者第二个动画不会运行
- python - 如何在python中将语音与列表进行比较
- ios - 我可以在 iOS 应用程序中收集捐赠信息,然后重定向到 safari
- firebase - Gradle 构建失败的 lint 问题反应原生
- html - 如何在网页背景中保留水印?
- python - NumPy Array 的 Python 子设置输出有点混乱
- javascript - 给定代码的 JavaScript 执行顺序无法理解
- iterm2 - 处理多个进程