Call PHP function from Twig template

纵饮孤独 提交于 2019-12-28 06:41:29

问题


I have a function in my controller that returns array of entities so in my twig template I do this to iterate over elements:

{% for groupName, entity in items %}
    <ul>
        <ul>
            {% for element in entity %}
                <li>{{ element.getLabel }}</li>
                <li><input type="text" name="detail[{{ element.getId }}]" id="pd_{{ element.getId }}" /><input type="text" name="price[{{ element.getId }}]" id="pd_price_{{ element.getId }}" /><input type="text" name="stock[{{ element.getId }}]" id="pd_stock_{{ element.getId }}" /></li>
            {% endfor %}
        </ul>
    </ul>
{% endfor %}

In my controller I have also this PHP function:

private function DetailCombination($arr, $level, &$result, $curr = array()) {
    for ($i = 0; $i < count($arr); $i++) {
        $new = array_merge($curr, array($arr[$i]));
        if ($level == 1) {
            sort($new);
            if (!in_array($new, $result)) {
                $result[] = $new;
            }
        } else {
            combinations($arr, $level - 1, $result, $new);
        }
    }
}

I can call it in this way:

for ($i = 0; $i < count($arr); $i++) {
    $this->DetailCombination($arr, $i + 1, $result);
}

// TEST
foreach ($result as $arr) {
    echo join(" ", $arr) . '<br>';
}

It's possible access to the PHP function from Twig template in order to get all the possible combinations of elements in entity? How?

** UPDATE **

This is the function that returns entities processed after by Twig Template:

private function getVariations($category_id) {
    $items = array();

    $em = $this->getDoctrine()->getManager();
    $entityCategory = $em->getRepository('CategoryBundle:Category')->find($category_id);

    foreach ($entityCategory->getProductDetails() as $entity) {
        if ($entity->getToProduct() == 1) {
            foreach ($entity->getDetailGroup() as $group) {
                if (!array_key_exists($group->getName(), $items)) {
                    $items [$group->getName()] = array();
                }

                $items [$group->getName()] [] = $entity;
            }
        } 
    }

    return $items;
} 

回答1:


Its not possible to access any PHP function inside Twig directly.

What you can do is write a Twig extension. A common structure is, writing a service with some utility functions, write a Twig extension as bridge to access the service from twig. The Twig extension will use the service and your controller can use the service too.

Take a look: http://symfony.com/doc/current/cookbook/templating/twig_extension.html

Cheers.




回答2:


There is already a Twig extension that lets you call PHP functions form your Twig templates like:

Hi, I am unique: {{ uniqid() }}.

And {{ floor(7.7) }} is floor of 7.7.

See official extension repository.




回答3:


You can check your all defined function by

$arr = get_defined_functions();
print_r($arr);

this will give you array of all functions in if your function exist in it you can use it like:

 {{ user.myfunction({{parameter}}) }}



回答4:


I am surprised the code answer is not posted already, it's a one liner.

You could just {{ categeory_id | getVariations }}

It's a one-liner:

$twig->addFilter('getVariations', new Twig_Filter_Function('getVariations'));



回答5:


While I agree with the comments about passing in variables from your controller you can also register undefined functions when setting up the twig environment

$twig->registerUndefinedFunctionCallback(function ($name) {
        // security
        $allowed = false;
        switch ($name) {
            // example of calling a wordpress function
            case 'get_admin_page_title':
                $allowed = true;
                break;
        }

        if ($allowed && function_exists($name)) {
            return new Twig_Function_Function($name);
        }

        return false;
    });

This is from the Twig recipe page

Haven't tried calling a function on an object as the original question requested




回答6:


I know this is an old thread. But with symfony 3.3 I did this:

{{ render(controller(
    'AppBundle\\Controller\\yourController::yourAction'
)) }}

Symfony docs




回答7:


If you really know what you do and you don't mind the evil ways, this is the only additional Twig extension you'll ever need:

function evilEvalPhp($eval, $args = null)
{
    $result = null;
    eval($eval);
    return $result;
}


来源:https://stackoverflow.com/questions/18665923/call-php-function-from-twig-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!