Skip to content

Instantly share code, notes, and snippets.

@punytan
Created April 4, 2011 04:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save punytan/901139 to your computer and use it in GitHub Desktop.
Save punytan/901139 to your computer and use it in GitHub Desktop.
for blog post - pjax
use strict;
use warnings;
use feature qw/say switch/;
use Data::Section::Simple;
use Text::Xslate;
use Plack::Request;
my $tx = Text::Xslate->new(
path => [ Data::Section::Simple->new->get_data_section ],
);
my $app = sub {
my $req = Plack::Request->new(shift);
my %data = ( %ENV,
TIME => scalar localtime,
PJAX => ($req->header('X-PJAX') ? 1 : 0)
);
say "----- X-PJAX is " . ($data{PJAX} ? 'TRUE' : 'FALSE');
my $type = $data{PJAX} ? 'pjax' : 'default';
my $res = $req->new_response(200);
$res->content_type('text/html; charset=utf-8');
given ($req->path_info) {
when ('/') {
$data{title} = "root";
$res->body( $tx->render("root-$type.tx", {data => \%data}) );
}
when ('/home') {
$data{title} = "/home";
$res->body( $tx->render("home-$type.tx", {data => \%data}) );
}
when ('/help') {
$data{title} = "/help";
$res->body( $tx->render("help-$type.tx", {data => \%data}) );
}
when ('/favicon.ico') {
$res->redirect("http://www.google.com/favicon.ico", 301);
}
default {
$res->status(404);
$res->body('Not Found');
}
}
return $res->finalize;
};
$app;
__DATA__
@@ home-pjax.tx
<: if $data.PJAX { :> <title><: $data.title :></title> <: } :>
<p> Hello, <: $data.USER :> </p>
@@ home-default.tx
: cascade base;
: override main -> { include "home-pjax.tx" }
: override title -> { "/hone" }
@@ help-pjax.tx
<: if $data.PJAX { :> <title><: $data.title :></title> <: } :>
<pre> <: $data | dump :> </pre>
@@ help-default.tx
: cascade base;
: override main -> { include "help-pjax.tx" }
: override title -> { "/help" }
@@ root-pjax.tx
<: if $data.PJAX { :> <title><: $data.title :></title> <: } :>
<p> pjax!! pjax!! pjax!!</p>
@@ root-default.tx
: cascade base;
: override main -> { include "root-pjax.tx" }
: override title -> { "root" }
@@ base.tx
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script src="http://pjax.heroku.com/jquery.pjax.js"></script>
<meta charset='utf-8'>
<title> <: block title -> { :> hello pjax <: } :> </title>
<script type="text/javascript">
$(function () {
$('a.js-pjax').pjax('#main');
})
</script>
</head>
<body>
: include "nav.tx"
<div>
: $data.TIME
</div>
<div id="main">
: block main -> { }
</div>
</body>
</html>
@@ nav.tx
<ul id="nav">
<li><a href="/" class="js-pjax">Index</a></li>
<li><a href="/home" class="js-pjax">Home</a></li>
<li><a href="/help" class="js-pjax">Help</a></li>
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment