0

I am creating a bake template using Twig for a cakePHP project. All what I want is to access the tables names of the database and their fields using twig to generate code based on these tables and fields.

I could easily access the tables names using (BUT THIS IS NOT WHAT I WANT)

use Cake\Datasource\ConnectionManager;

$db = ConnectionManager::get('default');
$collection = $db->getSchemaCollection();
$listTables = $collection->listTables(); 

I want to write something like that

{% set db = ConnectionManager.get('default') %}
{% set collection = db.getSchemaCollection() %}
{% set listTables = collection.listTables() %}

1 Answers1

0

You can't use PHP Class or functions in twig directly. Also it's not best practice to use it this way.

Best solutions are:

  1. Recommended: Put your login into the controller and pass the variable into the twig file. See passing variable section in the documentation here.

  2. Another way 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. Refer to this answer here.

Ishan Vyas
  • 15
  • 6
  • Actually I think I could use PHP Class or functions in twig directly. For example, If you open the default bake templates in a CakePHP project (vendor/cakephp/bake/src/template/bake/element/controller/any file), you will find that you could use some CakePHP framework functions directly in the twig file. The purpose of my question is to build a twig template to be used with the bake command. – Karim Reda Feb 18 '20 at 18:40
  • @KarimReda That's because Bake uses a [**Twig library**](https://github.com/cakephp/TwigView) that is explicitly built for use with CakePHP, and provides Twig extensions that make accessing helpers and certain functions possible out of the box. Using random PHP isn't possible neither with Twig, nor with the Twig view library used by Bake. You can however easily use events to inject variables into the bake view: **https://book.cakephp.org/bake/2/en/development.html** – ndm Feb 18 '20 at 21:22