twig:创建调用函数的自定义标记

SETUP:

  • Twig 1.13.1
  • PHP 5.4.3

PROBLEM:

I am needing help setting up a custom tag that calls a function that i have already built...


Current Code:

Template Code

{% set stories = get_latest_stories(2, sports) %}

{% for story in stories %}
    {{ story.headline }} <br>
{% endfor %}

Controller

$function = new Twig_SimpleFunction('getViewStories', function (section, limit) {
    return news_stories::getStories(section,limit);
});
$twig->addFunction($function);
$twig->render("storyList.html");

GOAL:

No with that said I would like to use a custom tag like

{% get_latest_stories 2 sports %}

to call the same function as above. The new way looks nicer and is easier to follow

Why not fetch your stories in the controller instead of the template? This does not seem like a job for the view layer...

So, something like this:

$twig->render("storyList.html", array(
    'stories' => news_stories::getStories($section, $limit)
));

Then, you'll have a stories variable available in your template.

here is simple example how to write twig extension Following code is taken from my unfinished project

function file_import($value){
    //some code here
    return $value;
}
$app['twig']->addFunction('file_import', new Twig_Function_Function('file_import'));

usage

{{ file_import('value') }}