开发者

Has CakePHP anything like Symfony's partials?

开发者 https://www.devze.com 2023-02-28 12:36 出处:网络
If you want to reuse code in views Symfony has two basic mechanisms: partials and slots. Partials are nice because you can define global partials (you can use them in any module) and module partials (

If you want to reuse code in views Symfony has two basic mechanisms: partials and slots. Partials are nice because you can define global partials (you can use them in any module) and module partials (they are only available in a certain module).

However, in CakePHP you only have regular templates and elements, the latter being available in every view, no matter which model/controller you are in.

Does CakePHP have anything like Symfony's partials? It would nice for example to avoid duplicating forms code for a model. You can have two templates (add a开发者_JS百科nd edit) that "include" a common form.

I know you can still use elements, but having a "local" elements directory for a module seems to keep things more organized. Can you suggest a workaround to simulate this?

Thanks!


Why not create a view (module_partial.ctp) inside the controller specific view directory. This will keep the code specific to the controller you want it to pertain to. So lets say you have a books controller. You want to add a BooksController specific form to some of your books views.

Create a view in the views/books/ directory called: search_partial.ctp

The search_partial.ctp will contain the HTML code you want.

Then, in any view, just call:

<?php echo $this->render('search_partial'); ?>

This will not prevent other controllers views from loading it, but it keeps the code base readable and segregated as you expect.

ALL of the globals would go into views/elements.


You can put elements in plugins.

You can do something like $this->element('something'); in the layout and have the element in a plugin and/or the main app views folder like such...

App/plugins/a_plugin/views/elements/something.ctp //only called when a controller from 'a_plugin' is called.

App/views/elements/something.ctp // called if the current plugin does not have 'something.ctp' in the elements folder

For not duplicating views like add/edit look at this https://github.com/infinitas/infinitas/blob/beta/app_controller.php#L389

0

精彩评论

暂无评论...
验证码 换一张
取 消