Как загрузить шаблон Twig вне папки Theme?

Я только изучаю шаблоны Twig, и мне трудно понять, как загрузить часть шаблона, которая находится в каталоге вне каталога текущей темы, чтобы их можно было использовать в других темах.

Я начинаю с простой загрузки части шаблона head.html, расположенной в директории core / tpls /. При использовании различных методов, которые я пробовал, я получаю следующую ошибку:

Неустранимая ошибка PHP: необработанное исключение Twig_Error_Loader с сообщением
«Невозможно найти шаблон» /home/ubuntu/workspace/core/tpls/head.html»( заглянул в: / home / ubuntu / workspace / themes / core) в «base.html» в
строка 5

Файл находится в каталоге и путь правильный, несмотря на то, что ошибка журнала говорит об обратном.

Мой base.html, расположенный в каталоге themes / core /, содержит пользовательскую функцию Twig для включения шаблона head.html, расположенного вне каталога темы:

<html lang="en" class="no-js">
<head>

{% include core.head %} // This is line 5 and throws the error and need to work correctly
// {% include core_head %} // This throws the error and should function the same as {% include core_head %}
// {% include tpl.head %} <-- If I use this, my function for grabbing templates from the theme works since I have a copy of the head.html in the theme dir too //

</head>
<body>

<header id="header">

{% include tpl.header %} // This works via the get_tpl() function

</header>

{% include tpl.breadcrumbs %} // This works too

[. . .]

Ненавижу загромождать это всем классом, но кому-то может быть полезно увидеть, в чем я не прав. Функция get_core_tpl () — это то, что я не могу заставить работать там, где другие мои функции get _ * () работают так, как должны. Смотрите мои комментарии там, а также обратите внимание на мои комментарии в функции befor_rendor ():

<?php

class Get_TPLs {

private $tpl_name,
$theme = 'core',
$tpl_array = array(
'breadcrumbs',
'content',
'cover',
'footer',
'head',
'header',
'sidebar'
);

public function before_load_content(&$file) {
$this->tpl_name = basename($file, '.md');
}

public function config_loaded(&$settings) {

if (isset($settings['core_tpl']))
$this->core_tpl = $settings['core_tpl'];

if (isset($settings['tpl_array']))
$this->tpl_array = $settings['tpl_array'];

if (isset($settings['theme']))
$this->theme = THEMES_DIR . $settings['theme'];
}

public function file_meta(&$meta) {

$config = $meta;
if (isset($config['slug'])):
$this->tpl_name = strtolower($config['slug']);
endif;
}

public function before_render(&$twig_vars, &$twig) {

//// ==== THIS IS CALLED WITH {% include core.[TEMPLATE_NAME] %} SEE Base.html ==== ////

// core/tpl/file
$twig_vars['core'] = $this->get_core_tpl();

//// === THIS IS A SIMPLIFIED VERSION OF THE ABOVE VAR - IT'S CALLED WITH {% include core_head %} but It throws the same error ==== ////

$twig_vars['core_head'] = CORE_TPL . '/head.html';

// theme/tpl/file
$twig_vars['tpl'] = $this->get_tpl();

// theme/tpl/views/file
$views = $this->get_views();
$twig_vars['views'] = $views;

// theme/content/file
$theme = $this->get_theme_content();
$twig_vars['theme'] = $theme;
//var_dump($twig_vars['theme']);
}

//// ==== THIS IS THE FUNCTION IN QUESTION ==== ////

private function get_core_tpl() {

foreach ($this->tpl_array as $value) {

$pattern = array('/ /', '/_/');
$name = preg_replace($pattern, '_', $value);
$core[$name] = CORE_TPL . $value . '.html';
}
return $core;
}

private function get_tpl() {

foreach ($this->tpl_array as $value) {

$pattern = array('/ /', '/_/');
$name = preg_replace($pattern, '_', $value);
$tpl[$name] = 'tpl/' . $value . '.html';
$page_tpl = $this->theme . '/tpl/' . $this->tpl_name . '-' . $value . '.html';

if (file_exists($page_tpl))
$tpl[$name] = '/tpl/' . $this->tpl_name . '-' . $value . '.html';
}
return $tpl;
}

private function get_theme_content() {
$content = $this->get_files($this->theme . '/content', '.md');
$content_data = array();

if (empty($content))
return;

foreach ($content as $key) {
$file = $this->theme . '/content/' . $key . '.md';
$pattern = array('/ /', '/-/');
$title = preg_replace($pattern, '_', strtolower($key));
$data = file_get_contents($file);
$content_data[$title] = \Michelf\MarkdownExtra::defaultTransform($data);
}
return $content_data;
}

private function get_views() {

$view_dir = $this->theme . '/tpl/views';
$views = $this->get_files($view_dir);

if (empty($views))
return;

$pattern = array('/ /', '/-/');

foreach ($views as $key) {
$name = preg_replace($pattern, '_', $key);
$view[$name] = 'tpl/views/' . $key . '.html';

if (file_exists($this->theme . '/tpl/' . $this->tpl_name . '-' . $key . '.html'))
$view[$name] = 'tpl/views/' . $this->tpl_name . '-' . $key . '.html';
}

if (!isset($view))
return array(0);

return $view;
}

// scrive.php lib
private function get_files($directory, $ext = '.html') {

if (!is_dir($directory))
return false;

$array_items = array();

if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {

$file = $directory . "/" . $file;
if (!$ext || strstr($file, $ext))
$array_items[] = basename($file, $ext);
}
closedir($handle);
}
return $array_items;
}
} ?>

Любая помощь будет оценена! Thnx

0

Решение

Задача ещё не решена.

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector