2

I've already a solution, but just for JavaScript. Unfortunately while-loops do not exist in Twig.

My Twig-target in JavaScript:

var x = 10; // this is an unknown number
var result = x;
while (100 % result !== 0) {
   result++;
}
console.log(result);

Any ideas how I do this in Twig?

What's my target: (not important if you already understood)

I want to get the first number after my unknown number, that satisfy the following condition:

100 divided by (the first number) equals a whole number as result.

EDIT: I have no access to PHP nor Twig-core.

4

2 回答 2

3

您可以制作一个 Twig 扩展,例如:

namespace Acme\DemoBundle\Twig\Extension;

class NumberExtension extends \Twig_Extension
{


    public function nextNumber($x)
    {
        $result = $x;
        while (100 % $result !== 0) {
            $result++;
        }
        return $result;
    }

    public function getFunctions()
    {
        return array(
            'nextNumber' => new \Twig_Function_Method($this, 'nextNumber'),
        );
    }


    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'demo_number';
    }
}

并在 bundle 的 service.xml 中定义:

<service id="twig.extension.acme.demo" class="Acme\DemoBundle\Twig\Extension\NumberExtension" >
    <tag name="twig.extension" />
</service>

然后在模板中使用它:

{{ nextNumber(10) }}

更新

一种(不是很好)但可能满足您需要的方法是执行以下操作:

{%  set number = 10  %}
{%  set max = number+10000  %}  {# if you can define a limit #}
{% set result = -1 %}
    {% for i in number..max %}
        {% if 100 % i == 0 and result < 0 %} {# the exit condition #}
            {% set result  = i %}
            {% endif %}
    {% endfor %}

<h1>{{ result }}</h1>

希望这有帮助

于 2015-02-19T11:32:09.603 回答
0

就我而言 - 我必须输出一个具有类似子对象的对象 - 包括具有预定义值的模板并设置正常的 if 条件。

有关更多信息,请参阅http://twig.sensiolabs.org/doc/tags/include.html

于 2016-05-30T22:58:19.420 回答