Example for using Twig in Laminas?

Using Laminas as “laminas/laminas-mvc-skeleton”, i would like to use twig as default template. I installes it:

"require": {
        "php": "^7.3",
        "laminas/laminas-component-installer": "^1.0 || ^2.1",
        "laminas/laminas-development-mode": "^3.2",
        "laminas/laminas-mvc": "^3.1.1",
        "laminas/laminas-cache": "^2.9.0",
        "laminas/laminas-db": "^2.10.0",
        "laminas/laminas-json": "^3.1.2",
        "laminas/laminas-log": "^2.11",
        "laminas/laminas-mvc-i18n": "^1.1.1",
        "laminas/laminas-psr7bridge": "^1.2.0",
        "laminas/laminas-session": "^2.9.1",
        "mezzio/mezzio-twigrenderer": "^2.6"
    },

but after that, the docs leave me allone, how to implement and use the twig templates correctly in my controllers:

class IndexController extends AbstractActionController {

    public function indexAction() {
		
        $view = new ViewModel(array(
			"message" => "Hello world",
		));
        
        $view->setTemplate("path/to/index.twig");
        
        return $view;
        
    }
    
}

The twig-temaplte file is loaded, but is displayed “as it is”, no twig handling.

Do somebody pls have an example of how to use twig within the controller function ?

Thanks in advance,
kim

Hello and welcome to our forums! :smiley:

You are mixing two different libraries that have different concepts for building applications.

laminas-mvc follows the typical software design pattern “model–view–controller” and with Mezzio you can create middleware applications, using the PSR-7 (HTTP Messages) and PSR-15 (HTTP Request Handlers) specifications.

For your installation this means you can not use the package “mezzio-twigrenderer” in a laminas-mvc based application. But a laminas-mvc application can be extended via modules and for the support of Twig you can use:

(Don’t worry about the name, the module also runs with the newer versions of laminas-mvc.)

1 Like