Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP: How to use a view element inside of a controller

I'm trying to figure out how to use one of my view elements inside of a controller...

I know, I know: "Don't do that!" (99% of the time this is the correct answer)

But I think I actually have a good reason. The action is handling an AJAX request which returns markup. The returned markup is a list which I display everywhere else using an element. So in an effort to keep my code DRY, I think it's appropriate to do this here.

Is this possible?

like image 574
emersonthis Avatar asked Apr 18 '13 13:04

emersonthis


1 Answers

Sometimes, you need to render a CakePhp element from a view and inject its content into the page using AJAX the same time. In this case rendering element as a regular view from controller is better than creating a dedicated view that just contains <?php echo $this->element('some_element') ?>, and may be done this way:

<?php
public function ajax_action() {
    // set data used in the element
    $this->set('data', array('a'=>123, 'b'=>456, 'd'=>678));

    // disable layout template
    $this->layout = 'ajax';

    // render!
    $this->render('/Elements/some_element');
}
like image 101
Serge S. Avatar answered Oct 06 '22 17:10

Serge S.