Created
January 15, 2014 19:25
-
-
Save ameliaikeda/8442685 to your computer and use it in GitHub Desktop.
Laravel AJAX trait addition for HTML5 History navigation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
trait AjaxTrait { | |
/** | |
* Setup the layout used by the controller. | |
* | |
* @return void | |
*/ | |
protected function setupLayout() { | |
if ( ! is_null($this->layout)) { | |
View::share("section", $this->section); | |
View::share("header", Config::get("osu.header")); | |
View::share("page", Request::segment(2) ?: "index"); | |
if (Request::ajax() or Input::has("ajax")) | |
$this->layout = View::make($this->ajax); | |
else | |
$this->layout = View::make($this->layout); | |
} | |
} | |
/** | |
* Execute an action on the controller. | |
* | |
* @param string $method | |
* @param array $parameters | |
* @return \Symfony\Component\HttpFoundation\Response | |
*/ | |
public function callAction($method, $parameters) { | |
$this->setupLayout(); | |
$response = call_user_func_array([$this, $method], $parameters); | |
// if there is already a response return it (POST), else it's a GET | |
if (is_null($response) and ! is_null($this->layout)) { | |
if (Request::ajax() or Input::has("ajax")) { | |
// raw response for AJAX to insert into the #content elem | |
$data = $this->layout->getEnvironment()->getShared(); | |
$html = str_replace(["\t", "\n", "\r\n"], "", $this->layout->render()); | |
return Response::json([ | |
"html" => $html, | |
"vars" => $data, | |
"translations" => [ | |
"section" => Lang::get("layout.menu.{$data["section"]}.{$data["section"]}"), | |
"page" => Lang::get("layout.menu.{$data["section"]}.{$data["page"]}") | |
] | |
]); | |
} else { | |
// ordinary response | |
return $this->layout; | |
} | |
} | |
return $response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment