Skip to content

Instantly share code, notes, and snippets.

@ameliaikeda
Created January 15, 2014 19:25
Show Gist options
  • Save ameliaikeda/8442685 to your computer and use it in GitHub Desktop.
Save ameliaikeda/8442685 to your computer and use it in GitHub Desktop.
Laravel AJAX trait addition for HTML5 History navigation
<?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