Git Product home page Git Product logo

fenom's People

Contributors

antonokulov avatar bakatrouble avatar bezumkin avatar bzick avatar daisuke-sama avatar dakiesse avatar electrica avatar emdm45 avatar evseevnn avatar get-web avatar ig0r74 avatar igorhim avatar jorgenpo avatar klkvsk avatar kulaginds avatar loki3000 avatar maxisoft-git avatar mungell avatar nekufa avatar neronmoon avatar pafnuty avatar paw34rus avatar pborreli avatar sleuthhound avatar sreenadh avatar tsukasa-mixer avatar vasia123 avatar wintersilence avatar xesau avatar zhabinka avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fenom's Issues

Параметр $parser_close в блоках

https://github.com/bzick/fenom/blob/master/docs/ext/tags.md#block-function

Последний параметр при определении блока вместо вставки напрямую в код возвращаемого значения вставляется как echo ...
Пример:

            $fenom->addBlockFunction("func", "func",
                    function(\Fenom\Tokenizer $tokens, \Fenom\Scope $scope){
                        return 'foreach($products as $key => $value) { extract($value); ';
                    },
                    function(\Fenom\Tokenizer $tokens, \Fenom\Scope $scope){
                        return '}';
                    });

Первый колбек вставляется прямо в код php, точно как я этого ожидал
Второй колбек вставляется с приставкой echo что полностью ломает логику

Unset переменных

Хотелось бы иметь возможность "ансетить" переменные в шаблоне. Что-то вроде такого {unset $var1 $var2 $var3}

AUTO_RELOAD в макросе

AUTO_RELOAD не срабатывает при правках внутри подключаемого макроса.

Way to call static methods (of Helpers for example) ?

Are there any ideas how can I call statis helpers in Fenom tpls. or maybe it is planned in nearest future ?

For example I have tried to use Fenom with Yii framework, everything is fine except the issue I can't have nice syntax to call satic helpers like this

<?php echo CHtml::link(...) ?>

P.S. [offtop] Nice job with template engine, internal are very hard to undertand, but I like the usage and performance :)

{exit} - Выход из шаблона

Есть ли возможность досрочно прекратить обработку шаблона командой, к примеру {exit}?
Вернув при этом обработанную часть шаблона.

Add compilation from code

Предлагаю сделать компиляцию из сырцов, сформированных в другом месте, что-то наподобие функции ниже. Ну и естественно желательно кеширование скомпилированного кода, например через через контрольные суммы кода.

/**
* Execute template and compile it from code
*
* @param string $template - code of template
* @param array $vars array of data for template
* @return Fenom\Render
*/

public function display_code($template_code, array $vars = array())
{
    return $this->compileCode($template_code)->display($vars);
}

Set\bind variables

Don't find in documentation how set template variables.
Fenom has analogues assign\append methods Smarty?

Один файл - один класс

Заметил, что в нескольких файлах (например Tokenizer.php) содержится более одного класса, такой вариант не вписывается ни в один из известных мне стандартов и осложняет отладку кода.
Хорошо бы "причесать" код под PSR-Х https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md

Вопросы по коду + баги

для чего используется опция disable_statics ? она встречается во всем коде только 1 раз
https://github.com/bzick/fenom/blob/master/src/Fenom.php#L69

Почему метод clean объявлен статическим и открытым? нашел его использование только в еще одном статическом методе rm, который кроме как в тестах нигде не используется.
https://github.com/bzick/fenom/blob/master/src/Fenom/Provider.php#L27

Рекурсивное включение и пропавшие переменные

Внимание!!! Только при выключенном force_compile!
Есть два кода шаблонов, при включении второго в первый, а затем второго во второй рекурсивно, пропадают переменные , объявленные в первом шаблоне, в данном случае $i

Первый шаблон
{foreach $sites as $i}
{if $i.sections!}
{include "site/sections.tpl" sections=$i.sections}
{/if}
{/foreach}

Второй шаблон
{foreach $sections as $ii}
{if $ii.childlist!}
{include "site/sections.tpl" sections=$ii.childlist}
{/if}
{/foreach}

По-моему за это отвечает строка 45 в файле Compiler.php

Notice: Undefined index: i in C:\server\www\dalimoshop2\www\system_cache\fenom\sections.tpl.1e9ef383.15.php on line 26

Прямая передача $i в шаблон в качестве переменной не помогает
{include "site/sections.tpl" i=$i sections=$ii.childlist}

Inconsistent codestyle

For example:

$scope["else"]

can be replaced with

$scope['else']

Why you use " without interpolation needs? Its:

  • slower (php engine checks if there is any interpolated vars)
  • make code style inconsistent

Can you replace all " with ' in cases when you do NOT need interpolation? Thanks.

Странная логика опций шаблонизатора

Использую версию 1.0.8. Какая-то фигня с опциями. Если вызвать шаблонизатор только с опцией AUTO_RELOAD и метод fetcch(), то он вообще не будет создавать кеш из скопилированных файлов. Почему? А если передать ему только FORCE_COMPILE или DISABLE_CACHE, то он зачем-то запретит использование методов php, хотя я его об этом не просил.

Получается, что вызвать кеширование без запрета методов php нельзя вообще. Так и должно быть или я что-то делаю не так?

Или это баг и надо использовать этот фикс?
klkvsk@6c6bd27

Объясните пожалуйста.

Рекурсия в макросе из родительского шаблона

Приветствую) столкнулся со следующей проблемой:
есть два шаблона:

test-child.html

{extends 'test-parent.html'} 
{block 'child'}
    {macro child_test(v, i)}
        child test - {$v}, i = {$i};<br/>
        {var $i = $i -1}
        {if $i > 0}
            {macro.child_test v=$v i=$i}
        {/if}
    {/macro}

    child call: <br/>
    {macro.child_test v = 'ok' i = 5}
{/block}

и собственно сам test-parent.html:

{macro parent_test(v, i)}
    parent test - {$v}, i = {$i};<br/>
    {var $i = $i -1}
    {if $i > 0}
        {macro.parent_test v=$v i=$i}
    {/if}
{/macro}

{block 'child'}{/block}

parent call:<br/>
{macro.parent_test v = 'ok' i = 5} <br/>

Что получается:
child call:
child test - ok, i = 5;
child test - ok, i = 4;
child test - ok, i = 3;
child test - ok, i = 2;
child test - ok, i = 1;
parent call:
parent test - ok, i = 5;

  • и вот на этом месте все падает, с ошибкой
    Fatal error: Class 'Symfony\Component\Yaml\Exception\RuntimeException' not found in ...\vendor\fenom\fenom\src\Fenom\Render.php on line 203

Скорее всего там должен быть обычный \RuntimeException('macro not found'), но это сути не меняет))) макрос не найден... на первой же рекурсивной итерации.

Хочу заметить, что в шаблоне test-child.html при работе макроса метод \Fenom\Render->getMacro($name) ни разу не вызывается. Если это поможет конечно чем-то.

Версия - 1.4.8

Add operators 'in' and 'is'

Examples:
$a in [1, 2, 3], use in_array() or isset() by assoc array
$a in "string", use strpos()
$a in $b, detect dynamically
allow not in operator

$a is integer (double, string, array, object, iterable, null)
$a is scalar
$a is number
$a is MyClass or $a is \MyClass, means instaceof
$a is empty means empty()
$a is set means isset()
$a is odd
$a is even
$a is $b mean ===
$a is template check if template with name $a exists
allow is not operator

Ошибки в HTML комментариях -> Uncaught exception

При работе заметил что HTML комментарии тоже компилируются. Зачем ? Я чего-то упускаю или это баг ?
пример

<body>
    <!--<h2>{$order_data->order_number|number_fosrmat:2}</h2>-->
</body>

была случайно (а потом и специально) допущена ошибка в написании фунции number_foSrmat()
на что ругается Fenom\Template->parseModifier( )

исправляю на привычный number_format - всё работает.
после чего скомпилтрованый шаблон выглядит так

<body>
    <!--<h2><?php
/* single_order.tpl:9: {$order_data->order_number|number_format:2} */
 echo number_format($tpl["order_data"]->order_number, 2); ?></h2>-->
</body>

Nested function calls

When using custom functions, it would be great to be able to nest them like so:
{func1 "foo" (func2 "bar")}
And this would be rendered as:
<?= func1("foo", func2("bar")); ?>
Is this possible?

Add dynamic loader for modifiers [draft]

Try create load-system on classes and autoload

Adding modifier

  • All modifier stored in class as methods, like Fenom\Modifier class.
  • Add class to Fenom storage: $fenom->addModifiersSource('Vendor\MyModifiers'). Second argument is boolean - append or prepend, by default prepend. Fenom do not parse class yet and do nothing with him. Just store.
  • If need parse template starts parse stored classes by rules: modifiers name == methods name

good points:

  • all modifiers autoloaded by user's rule
  • if modifier is static method we cat put in template as is. Increase perfomance.
    bad points:
  • add class manualy

Autoescape option

Add Fenom::AUTOESCAPE_VARS for escape each output variable via
htmlspecialchars($var, ENT_QUOTES, 'UTF-8');

Рекурсивые макросы

Очень хочется иметь возможность ссылать на подшаблон (макрос) внутри его самого. По аналогии с рекурсивной функцией. Это необходимо, когда нужно выстроить на странице таблицу из массива произвольной вложенности.

Наследование и вложенные блоки

Есть предложение реализовать обработку вложенных блоков. Например:

template.level1.html:

<html>
  <body>
    <div class="container">
       {block 'body'}{/block}
       <hr/>
       <footer>
         {block 'footer'}
            <p>&copy; Company 2014</p>
         {/block}
       </footer>
    </div>
  </body>
</html>

template.level2.html:

{extends 'template.level1.html'}

{block 'body'}
  ...(html code)...
  {block 'menu'}default menu{/block} 
  ...(html code)...
  {block 'content'}{/block} 
  ...(html code)...
{/block}     

template.level3.html:

{extends 'template.level2.html'}

{block 'menu'}
  menu
{/block} 

{block 'content'} 
   content
{/block} 

{block 'footer'}
   custom footer
{/block}

Сейчас если есть хоть один вложенный блок, то родительский блок вообще не показывается.

Add magic variable (accessor)

Add support unnamed magic variable $.
Variable allow access to global variables and internal info:
$.get access to $_GET
$.post access to $_POST
$.cookie access to $_COOKIE
$.session access to $_SESSION
$.globals access to $GLOBALS
$.request access to $_REQUEST
$.files access to $_FILES
$.server access to $_SERVER
$.tpl.name returns current template name
$.tpl.schema returns current load schema of template
$.version returns version of the Fenom
$.const access to constants
Accessor will be in read-only mode

Allow modifiers for function calls

Not sure if I'm doing it right, but that does not work:
Current year: {time()|date:"Y"}
Throws me "Unexpected token '|' in <...>, near '{time()|' <- there"

Instead, one could use:
Current year: {var $time = time()} {$time|date:"Y"}
but that does not look pretty.

Add {parent} support

Current algorithm does not support access to parents block from child. Small refactoring required.

Add supports pre-filters, filters, post-filters functions for template

Pre-filters functions get the source of template (Fenom syntax) and can change it
Post-filters functions get the source template (PHP code) and can change it
Filters functions get texts (multiple invoke) between fenom's tags and can change it

All filters are invoked at compile time.

Question/Bug: Не могу завести на Windows. Provider for 'C' not found

Win7 64, WAMP (PHP 5.4.3, Apache 2.2.22)

Решил попробовать Квик-старт

define('BASE_PATH', __DIR__); // C:\Users\<username>\Dropbox\work\fenomTPLs
define('TEMPLATE_PATH', BASE_PATH . DIRECTORY_SEPARATOR . 'templates'); // C:\Users\<username>\Dropbox\work\fenomTPLs\templates
define('COMPILED_PATH', TEMPLATE_PATH . DIRECTORY_SEPARATOR . 'compiled'); // C:\Users\<username>\Dropbox\work\fenomTPLs\templates\compiled

$fenom = Fenom::factory(TEMPLATE_PATH, COMPILED_PATH, Fenom::AUTO_RELOAD);
$fenom->display(TEMPLATE_PATH. '\order.tpl', $rawData);

на что получаю InvalidArgumentException : Provider for 'C' not found
Дебаг привел к Fenom\Template.php:173

вызвал сомнения весь блок с 166 - 173

$this->_crc = crc32($this->_name);
        if ($provider = strstr($name, ':', true)) {
            $this->_scm = $provider;
            $this->_base_name = substr($name, strlen($provider) + 1);
        } else {
            $this->_base_name = $name;
        }
        $this->_provider = $this->_fenom->getProvider($provider);

if-блок с одним = ?!
Fenom->getProvider читает из Fenom->$_providers. Пишет туда только Fenom->addProvider который вызываеться только из теста (CustomProviderTest.php)

Было что-то упущено или я недопонимаю чего-то елемнтарного ?

Как можно задать compile_id

Возможно ли задать уникальный compile_id для скомпилированных файлов шаблона ? Предметно как в smarty $this->smarty->compile_id чтобы получить файл который скомпилирован по образцу {compile_id}_{tpl_file}

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

Compile error with boolean operators

{if max(2, 4) > 1 && max(2, 3) < 1} block1 {else} block2 {/if}

crushes with message:

Fenom\Error\CompileException: Unexpected token '<' in runtime.tpl line 1, near '{if max(2, 4) > 1 && max(2, 3) <' <- there

Потеря переменных при рекурсивном включении шаблона

Повторная проблема. Включаю рекурсивно шаблон сам в себя и теряются переменные. Полное описание - ниже. Версия fenom текущая. Лучше смотреть в режиме html

Есть вот такой массив $eprice_menu

Массив :
Array
(
[2875] => Array
(
[id] => 1
[title] => ОСНОВНАЯ ГРУППА
[orig_id] => 2875
[orig_parent_id] => 0
[count_object] => 85
[order_sort] => 0
[is_imp] => 100
[unit_id] => 1
[selected] => 1
[childlist] => Array
(
[7] => Array
(
[id] => 2
[title] => Весовые Отечественные сыры
[orig_id] => 7
[orig_parent_id] => 2875
[count_object] => 121
[order_sort] => 0
[is_imp] => 127
[unit_id] => 1
[selected] => 1
[childlist] => Array
(
[37022] => Array
(
[id] => 3
[title] => Сыры ТМ "Сырная тарелка"
[orig_id] => 37022
[orig_parent_id] => 7
[count_object] => 4
[order_sort] => 0
[is_imp] => 11
[unit_id] => 1
[selected] => 1
[childlist] =>
)

                                [5088] => Array
                                    (
                                        [id] => 15
                                        [title] => Сыры прочие
                                        [orig_id] => 5088
                                        [orig_parent_id] => 7
                                        [count_object] => 10
                                        [order_sort] => 0
                                        [is_imp] => 10
                                        [unit_id] => 1
                                        [selected] => 0
                                        [childlist] => 
                                    )

                                [32311] => Array
                                    (
                                        [id] => 6
                                        [title] => Сыры Умалат
                                        [orig_id] => 32311
                                        [orig_parent_id] => 7
                                        [count_object] => 17
                                        [order_sort] => 0
                                        [is_imp] => 9
                                        [unit_id] => 1
                                        [selected] => 0
                                        [childlist] => 
                                    )

                                [9862] => Array
                                    (
                                        [id] => 7
                                        [title] => Сыры Ичалковские
                                        [orig_id] => 9862
                                        [orig_parent_id] => 7
                                        [count_object] => 21
                                        [order_sort] => 0
                                        [is_imp] => 8
                                        [unit_id] => 1
                                        [selected] => 0
                                        [childlist] => 
                                    )

                                [7503] => Array
                                    (
                                        [id] => 8
                                        [title] => Сыры Чувашия
                                        [orig_id] => 7503
                                        [orig_parent_id] => 7
                                        [count_object] => 7
                                        [order_sort] => 0
                                        [is_imp] => 7
                                        [unit_id] => 1
                                        [selected] => 0
                                        [childlist] => 
                                    )

                                [8517] => Array
                                    (
                                        [id] => 9
                                        [title] => Сыры Сармич
                                        [orig_id] => 8517
                                        [orig_parent_id] => 7
                                        [count_object] => 8
                                        [order_sort] => 0
                                        [is_imp] => 6
                                        [unit_id] => 1
                                        [selected] => 0
                                        [childlist] => 
                                    )

                                [34603] => Array
                                    (
                                        [id] => 10
                                        [title] => Сыры Стародубские
                                        [orig_id] => 34603
                                        [orig_parent_id] => 7
                                        [count_object] => 12
                                        [order_sort] => 0
                                        [is_imp] => 5
                                        [unit_id] => 1
                                        [selected] => 0
                                        [childlist] => 
                                    )

                                [8771] => Array
                                    (
                                        [id] => 11
                                        [title] => Сыры Тамбовские
                                        [orig_id] => 8771
                                        [orig_parent_id] => 7
                                        [count_object] => 5
                                        [order_sort] => 0
                                        [is_imp] => 4
                                        [unit_id] => 1
                                        [selected] => 0
                                        [childlist] => 
                                    )

                                [30270] => Array
                                    (
                                        [id] => 12
                                        [title] => Сыры Белебей
                                        [orig_id] => 30270
                                        [orig_parent_id] => 7
                                        [count_object] => 17
                                        [order_sort] => 0
                                        [is_imp] => 3
                                        [unit_id] => 1
                                        [selected] => 0
                                        [childlist] => 
                                    )

                                [30269] => Array
                                    (
                                        [id] => 13
                                        [title] => Сыры Майна
                                        [orig_id] => 30269
                                        [orig_parent_id] => 7
                                        [count_object] => 6
                                        [order_sort] => 0
                                        [is_imp] => 2
                                        [unit_id] => 1
                                        [selected] => 0
                                        [childlist] => 
                                    )

                                [40749] => Array
                                    (
                                        [id] => 5
                                        [title] => 02.1 Народные сословия
                                        [orig_id] => 40749
                                        [orig_parent_id] => 7
                                        [count_object] => 7
                                        [order_sort] => 0
                                        [is_imp] => 0
                                        [unit_id] => 1
                                        [selected] => 0
                                        [childlist] => 
                                    )

                                [40269] => Array
                                    (
                                        [id] => 4
                                        [title] => Сыры ТМ Ласкава
                                        [orig_id] => 40269
                                        [orig_parent_id] => 7
                                        [count_object] => 7
                                        [order_sort] => 0
                                        [is_imp] => 0
                                        [unit_id] => 1
                                        [selected] => 0
                                        [childlist] => 
                                    )

                            )

                    )

                [11345] => Array
                    (
                        [id] => 42
                        [title] => Весовые Премиум сыры
                        [orig_id] => 11345
                        [orig_parent_id] => 2875
                        [count_object] => 40
                        [order_sort] => 0
                        [is_imp] => 127
                        [unit_id] => 1
                        [selected] => 0
                        [childlist] => Array
                            (
                                [39059] => Array
                                    (
                                        [id] => 44
                                        [title] => СЫРЫ ПОЛУТВЕРДЫЕ Премиум весовые.
                                        [orig_id] => 39059
                                        [orig_parent_id] => 11345
                                        [count_object] => 19
                                        [order_sort] => 0
                                        [is_imp] => 0
                                        [unit_id] => 1
                                        [selected] => 0
                                        [childlist] => 
                                    )

                                [39060] => Array
                                    (
                                        [id] => 45
                                        [title] => СЫРЫ с БЕЛОЙ плесневой культурой Премиум весовые.
                                        [orig_id] => 39060
                                        [orig_parent_id] => 11345
                                        [count_object] => 3
                                        [order_sort] => 0
                                        [is_imp] => 0
                                        [unit_id] => 1
                                        [selected] => 0
                                        [childlist] => 
                                    )

                                [39061] => Array
                                    (
                                        [id] => 46
                                        [title] => СЫРЫ с ГОЛУБОЙ плесневой культурой Премиум весовые.
                                        [orig_id] => 39061
                                        [orig_parent_id] => 11345
                                        [count_object] => 6
                                        [order_sort] => 0
                                        [is_imp] => 0
                                        [unit_id] => 1
                                        [selected] => 0
                                        [childlist] => 
                                    )

                                [39058] => Array
                                    (
                                        [id] => 43
                                        [title] => СЫРЫ ТВЕРДЫЕ Премиум весовые.
                                        [orig_id] => 39058
                                        [orig_parent_id] => 11345
                                        [count_object] => 12
                                        [order_sort] => 0
                                        [is_imp] => 0
                                        [unit_id] => 1
                                        [selected] => 0
                                        [childlist] => 
                                    )

                            )

                    )

                [39070] => Array
                    (
                        [id] => 29
                        [title] => Весовые Прибалтийские сыры
                        [orig_id] => 39070
                        [orig_parent_id] => 2875
                        [count_object] => 12
                        [order_sort] => 0
                        [is_imp] => 127
                        [unit_id] => 1
                        [selected] => 0
                        [childlist] => Array
                            (
                                [39049] => Array
                                    (
                                        [id] => 32
                                        [title] => Прочие прибалтийский сыры
                                        [orig_id] => 39049
                                        [orig_parent_id] => 39070
                                        [count_object] => 3
                                        [order_sort] => 0
                                        [is_imp] => 0
                                        [unit_id] => 1
                                        [selected] => 0
                                        [childlist] => 
                                    )

                                [39046] => Array
                                    (
                                        [id] => 30
                                        [title] => Рокишкио Литва
                                        [orig_id] => 39046
                                        [orig_parent_id] => 39070
                                        [count_object] => 5
                                        [order_sort] => 0
                                        [is_imp] => 0
                                        [unit_id] => 1
                                        [selected] => 0
                                        [childlist] => 
                                    )

                                [39047] => Array
                                    (
                                        [id] => 31
                                        [title] => Сваля Литва
                                        [orig_id] => 39047
                                        [orig_parent_id] => 39070
                                        [count_object] => 4
                                        [order_sort] => 0
                                        [is_imp] => 0
                                        [unit_id] => 1
                                        [selected] => 0
                                        [childlist] => 
                                    )

                            )

                    )

                [39066] => Array
                    (
                        [id] => 55
                        [title] => Весовые свежие и  рассольные сыры
                        [orig_id] => 39066
                        [orig_parent_id] => 2875
                        [count_object] => 6
                        [order_sort] => 0
                        [is_imp] => 127
                        [unit_id] => 1
                        [selected] => 0
                        [childlist] => Array
                            (
                                [39068] => Array
                                    (
                                        [id] => 56
                                        [title] => Арла Дания
                                        [orig_id] => 39068
                                        [orig_parent_id] => 39066
                                        [count_object] => 4
                                        [order_sort] => 0
                                        [is_imp] => 0
                                        [unit_id] => 1
                                        [selected] => 0
                                        [childlist] => 
                                    )

                                [39069] => Array
                                    (
                                        [id] => 57
                                        [title] => Хохланд
                                        [orig_id] => 39069
                                        [orig_parent_id] => 39066
                                        [count_object] => 2
                                        [order_sort] => 0
                                        [is_imp] => 0
                                        [unit_id] => 1
                                        [selected] => 0
                                        [childlist] => 
                                    )

                            )

                    )
                .........
            )
        ........
    )
.......

)

И такой шаблон

    {var $curdepth=$depth+1} {foreach $eprice_menu as $k=>$v} {switch $curdepth} {case 1}

    {$v.title}

    {case 2} {$v.title} {case 3} {$v.title} {/switch} {if $v.childlist! && $v.childlist} {include 'eprice_menu.tpl' $eprice_menu=$v.childlist $parent_view=$v.selected $depth=$curdepth} {/if} {/foreach}

Изначально включается в другой шаблон таким образом

{include 'eprice_menu.tpl' $parent_view=0 $depth=0}

Скомпилированный шаблон

    $v} _/ if($tpl["eprice_menu"]) { foreach($tpl["eprice_menu"] as $tpl["k"] => $tpl["v"]) { ?>

    <li class='act' style='display:block;'>









    getStorage()->getTemplate('eprice_menu.tpl')->display(array("0" => $tpl["eprice_menu"] = $tpl["v"]["childlist"],"1" => $tpl["parent_view"] = $tpl["v"]["selected"],"2" => $tpl["depth"] = $tpl["curdepth"])+(array)$tpl); ?>

128, 'provider' => false, 'name' => 'eprice_menu.tpl', 'base_name' => 'eprice_menu.tpl', 'time' => 1389852718, 'depends' => array ( 0 => array ( 'eprice_menu.tpl' => 1389852718, ), ), 'macros' => array(),
    ));

И результат вывода (при $force_compile==true)

Tests does not consider timezones

// tests/cases/Fenom/TemplateTest.php:103
"time" => 1343323616,

One time, two dates

date_default_timezone_set('Asia/Irkutsk');
echo Date('Y m d', 1343323616) . "\n"; // 2012 07 27
date_default_timezone_set('Europe/Moscow');
echo Date('Y m d', 1343323616) . "\n"; // 2012 07 26

Congratulations!

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

Great work! You are doing a great template system! It really is more convenient than Smarty! I plan to use it in combat projects. Please, continue to develop! It turns out is a good thing!

P.S.: тикет можно закрывать после прочтения =)

обрабатывать var в унаследованных шаблонах

Сейчас из шаблона, наследующего другой шаблон, берутся только блоки. Было бы неплохо брать так же тег var, чтобы можно было менять значения переданных переменных. Например, в числе прочих передана переменная $title. Мы делаем {var $title = $title|upper}, этот код компилится и вставляется в начале сгенеренного шаблона. Получается некий аналог блоков, но часто удобнее работать именно с переменной.

PHP Notice: Indirect modification of overloaded property Fenom\\Template::$b

There are many messages in apache logs like

[Sun Apr 27 00:59:44 2014] [error] [client 127.0.0.1] PHP Notice:  Indirect modification of overloaded property Fenom\\Template::$b has no effect in /var/www/<some dir>/vendor/fenom/fenom/src/Fenom/Template.php(437) : eval()'d code on line 295, referer: <some url>

What does it mean? Thank's

Undefined variable: _tpl1

При рекурсивном включении макроса вылетает натайс:
Undefined variable: _tpl1 in .../results.tpl.275ae050.f.php on line 768
стек:
6 0.0051 861248 Fenom->display( ) ../View.php:60
7 0.0076 989096 Fenom\Render->display( ) ../Fenom.php:676
8 0.0076 989608 Closure->__invoke( ) ../Render.php:215
9 0.0076 989640 Fenom->{closure:../compiled/results.tpl.275ae050.f.php:3-775}( ) ../Render.php:215

Class 'Fenom\Provider' not found in ..\Fenom.php on line 264

Привет, никак в толк не пойму что не так подключаю, пытаюсь запустить из Denwer'а, Windows7, php 5.3.13, Apache 2.2.22.

include_once ('./library/Fenom.php');
define('BASE_PATH', __DIR__);
define('TEMPLATE_PATH', BASE_PATH . DIRECTORY_SEPARATOR . 'templates');
define('COMPILED_PATH', TEMPLATE_PATH . DIRECTORY_SEPARATOR . 'compiled');

$fenom = Fenom::factory(TEMPLATE_PATH, COMPILED_PATH, Fenom::AUTO_RELOAD);
$fenom->display('index.tpl', $rawData);

Выдает ошибку:

Class 'Fenom\Provider' not found in Z:\home\fenom\www\library\Fenom.php on line 264

Add modifier loader [draft]

Try create load-system on classes and autoload

Adding modifier

  • All modifier stored in class as methods, like Fenom\Modifier class.
  • Add class to Fenom storage: $fenom->addModifiersSource('Vendor\MyModifiers'). Second argument is boolean - append or prepend, by default prepend. Fenom do not parse class yet and do nothing with him. Just store.
  • If need parse template starts parse stored classes by rules: modifiers name == methods name

good points:

  • all modifiers autoloaded by user's rule
  • if modifier is static method we cat put in template as is. Increase perfomance.
    bad points:
  • add class manually

unset вернется?

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

Provider и Cache

Может имеет смысл делегировать функционал для работы с кешем классу Provider? Было бы очень удобно

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.