Search code examples
twigtwig-extension

Twig: while-workaround


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.


Solution

  • You can make a Twig extension like:

    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';
        }
    }
    

    And define it in the service.xml of the bundle:

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

    Then use it in the template:

    {{ nextNumber(10) }}
    

    UPDATE

    A (not so great) approach but that possibly satisfy your needed is to do something like this:

    {% 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>
    

    Hope this helps