我正在创建一个插件,它与我正在开发的主题直接相关。我的插件可以呈现一些内置模板(当我调用一个短代码时,插件用正确的测试板回复);这些模板现在是PHP文件。我会用木材来渲染这些文件。
不幸的是,第261期仍然开放。我不知道如何在当前的木材代码库中获得预期的行为。
预期行为:
我怎样才能得到这个?现在我已经在我的主题上使用模板进行了测试,我只需调用Timber。render()代码>但我没有包含本地路径。
标准PHP插件代码:
// On plugin load
add_shortcode('render_social_icons', array($this, 'render_social_icons'));
public function render_social_icons($atts, $content)
{
$atts = shortcode_atts(array(
'class' => '',
'el-class' => '',
'link-class' => '',
'icon-class' => '',
'size' => '',
), $atts);
ob_start();
?>
<ul class="social-icons shortcode <?php echo $atts['class']; ?>">
<?php
$socials = my_socials_links();
foreach ($socials as $social) :?>
<?php
$id = $social['id'];
$title = $social['name'];
$baseurl = $social['baseurl'];
$icon = $social['icon'];
$social_data = get_theme_mod($id);
if (!empty($social_data)) :?>
<li class="<?php echo $id; ?> <?php echo $atts['el-class']; ?>">
<a target="_blank" title="<?php echo $title; ?>" href="<?php printf($baseurl, $social_data); ?>"
class="<?php echo $atts['link-class']; ?>">
<i class="<?php echo $icon; ?> <?php echo $atts['icon-class']; ?> <?php echo $atts['size']; ?>"></i>
</a>
</li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
<?php
return ob_get_clean();
}
转换后的Timber函数(仍然是一个插件文件):
// On plugin load
add_shortcode('render_social_icons', array($this, 'render_social_icons'));
public function render_social_icons($atts, $content)
{
$atts = shortcode_atts(array(
'class' => '',
'el-class' => '',
'link-class' => '',
'icon-class' => '',
'size' => '',
), $atts);
return Timber.compile('shortcodes/social.twig', array(atts, my_socials_links());
}
shortcode/social。twig
位于当前主题文件夹内,我想从plugin foder加载此twig模板文件。
Timber无需注册细枝文件即可将其用于Timber::compile
。您只需要提供文件的完整路径作为第一个参数。要在插件中执行此操作,您需要使用plugin\u dir\u path()
获取插件目录路径。要使用示例代码,可以执行以下操作。
public function render_social_icons($atts, $content) {
$plugin_path = plugin_dir_path( __FILE__ );
$atts = shortcode_atts(array(
'class' => '',
'el-class' => '',
'link-class' => '',
'icon-class' => '',
'size' => '',
), $atts);
return Timber::compile($plugin_dir_path . '/twig/social.twig', $atts);
}
关于Timber::compile
最酷的一点是,您可以传递一个路径数组,而Timber将使用它找到的第一个文件。这意味着您可以允许主题覆盖社交。细枝
文件位置,文件位于已注册的木材路径中。例如,可以将最后一行更改为:
return Timber::compile(array('social-shortcode-custom.twig', $plugin_dir_path . '/twig/social.twig'), $atts);
然后,Timber将变量传递到名为social shortcode custom的文件中。树枝
位于已注册的木材位置(如果存在),如果没有,则返回到插件中的文件。
我不确定这是否会影响事情,但是我不知道您在编译函数中使用的语法。我一直看到并使用静态方法Timber::comload()
,但您使用的是Timber.compile()
。木材最近更新很快,所以也许你看到了我错过的东西?