Skip to content

Instantly share code, notes, and snippets.

@rakeshtembhurne
Created July 19, 2013 10:10
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save rakeshtembhurne/6038128 to your computer and use it in GitHub Desktop.
Save rakeshtembhurne/6038128 to your computer and use it in GitHub Desktop.
CakePHP: Render view in a variable inside controlller
<?php
$view = new View($this, false);
$view->set(compact('some', 'vars'));
$html = $view->render('view_name');
Copy link

ghost commented Nov 28, 2014

Thank you.

@TamasBarta
Copy link

Thanks! Works with "cakephp/cakephp": "2.6.*". I'd add, that to render without the layout, just set $view->layout = null, or at least that's what worked for me.

@JayWalker512
Copy link

This still works in 3.0.*, with slightly tweaked code:

$view = new View($this->request);
$view->set(compact('some', 'vars'));
$html = $view->render('view_name');

Very helpful, thank you!

@amitrajan1982
Copy link

public function index()
{
$this->set(compact('users'));
$this->set('_serialize', ['users']);

}

i am not able to call simple view from my controller ..pls help.

@Dayglor
Copy link

Dayglor commented Feb 8, 2017

Thanks!!

@MikeOtown
Copy link

what if the View is for a different Controller?

@arturmamedov
Copy link

Thank u very much! Work like a charm! (also i created empty.ctp Layout, but how suggest @TamasBarta it can be disabled)

@fshahzad
Copy link

For different controller view just pass the path of the .ctp file in the render() method call...

$view = new View($your_controller || $this, false);

$view->layout = false; //if you donot want to render it in template

$view->set('some_data', $some_data);

$html = $view->render('../back/path/to/the/other/controller/ctp/file.ctp');

@celsowm
Copy link

celsowm commented Aug 22, 2020

	public function template(){
		
		$entity = TableRegistry::get('MyTable')->find()->last();
		
		$view = new View($this->request);
		$view->layout = false;
		$view->set(compact('entity'));
		$html = $view->render('Etiqueta'.DS.'por_aviso');
		
		debug($html);
		
	}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment