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

后端 未结 6 1127
情深已故
情深已故 2020-12-17 20:52

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

6条回答
  •  时光说笑
    2020-12-17 21:21

    I know this is an old question and other people have already given basically the same answer, but I want to point out that this approach (provided by Serge S.) ...

    set('data', array('a'=>123, 'b'=>456, 'd'=>678));
    
        // disable layout template
        $this->layout = 'ajax';
    
        // render!
        $this->render('/Elements/some_element');
    }
    

    ...is not a hacky workaround, but is in fact the recommended approach from the CakePHP docs for this common and legitimate use case:

    If $view starts with ‘/’, it is assumed to be a view or element file relative to the /app/View folder. This allows direct rendering of elements, very useful in AJAX calls.

    (Again: Credit to Serge S. for the code above)

提交回复
热议问题