简体   繁体   English

Cakephp:如何使用 Twig 获取数据库表名列表

[英]Cakephp: How to get a list of the database table names using Twig

I am creating a bake template using Twig for a cakePHP project.我正在使用 Twig 为 cakePHP 项目创建烘焙模板。 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.我想要的只是使用 twig 访问数据库的表名及其字段,以根据这些表和字段生成代码。

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() %}

You can't use PHP Class or functions in twig directly.您不能直接在 twig 中使用 PHP 类或函数。 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.推荐:将您的登录信息放入控制器并将变量传递到 twig 文件中。 See passing variable section in the documentation here .请参阅此处文档中的传递变量部分。

  2. Another way you can do is write a Twig extension.另一种方法是编写一个 Twig 扩展。 A common structure is, writing a service with some utility functions, write a Twig extension as bridge to access the service from twig.一个常见的结构是,编写具有一些实用程序功能的服务,编写一个 Twig 扩展作为从 twig 访问服务的桥梁。 The Twig extension will use the service and your controller can use the service too. Twig 扩展将使用该服务,您的控制器也可以使用该服务。 Refer to this answer here .请在此处参考此答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM