Ad

How Do I Add A Twig Test In October CMS?

- 1 answer

This is working well in my registerMarkupTags function.

            'functions' => [
                'isNumeric' => function($value) { return is_numeric($value); }

So I can write:

{% if isNumeric(result) %}

I want to make it a test e.g.

{% if result is numeric %}
Ad

Answer

You can add a custom extension for twig

Source: https://tutorialmeta.com/october-cms/october-cms-extend-custom-twig-markup

Add below code to your plugin.php file

// other imports
use Twig\Extension\AbstractExtension as TwigExtension;

// our extension class 
// you can declare here inside plugin.php file or in your `plugin\classes` file
// for simplicity we have declared it here

class MyTwigExtension extends TwigExtension {
    public function getTests() {
        return [
            new \Twig\TwigTest('numeric', function ($value) {
                return is_numeric($value);
            })
        ];
    }
}

class Plugin extends PluginBase {
    public function boot() {
        Event::listen('cms.page.beforeDisplay', 
            function ($controller, $url, $page) {
                $controller->getTwig()->addExtension(new MyTwigExtension);
            }
        );
    }
    // other code
}

Now from your markup

{% if 12 is numeric %}
    yes numeric.
{% else %}
    not a numeric.
{% endif %}

if any doubt please comment.

Ad
source: stackoverflow.com
Ad