Skip to content

Instantly share code, notes, and snippets.

@yappo
Last active August 29, 2015 13:58
Show Gist options
  • Save yappo/9949763 to your computer and use it in GitHub Desktop.
Save yappo/9949763 to your computer and use it in GitHub Desktop.
#!perl -w
use strict;
use Text::Xslate;
use Text::Xslate::Util qw(hash_with_default);
my $DEBUG = 1;
# bad pratice
{
my %vars;
my $vars_ref = $DEBUG ? hash_with_default(
\%vars,
sub { "FILL ME/$_[0]" }
) : \%vars;
my $tx = Text::Xslate->new();
print $tx->render_string(<<'T', $vars_ref);
Hello, <: if ($oops) { :>sursen<: } :> world!
T
# => Hello, sursen world!
}
# best practice
{
my %vars;
my $vars_ref = $DEBUG ? hash_with_default(
\%vars,
sub {
Text::Xslate->print(
Text::Xslate::mark_raw('<span style="color: red; font-size: 1.8em;">'),
"FILL ME/$_[0]",
Text::Xslate::mark_raw('</span>')
);
return undef;
}
) : \%vars;
my $tx = Text::Xslate->new();
print $tx->render_string(<<'T', $vars_ref);
Hello, <: if ($oops) { :>sursen<: } :> world!
T
# => Hello, <span style="color: red; font-size: 1.8em;">FILL ME/oops</span> world!
}
# great
sub hash_with_default_walker {
my($base_key, %hash) = @_;
my $result = {};
for my $key (keys %hash) {
if (ref($hash{$key}) eq 'HASH') {
$result->{$key} = hash_with_default_walker("$base_key$key.", %{ $hash{$key} });
} else {
$result->{$key} = $hash{$key};
}
}
hash_with_default(
$result,
sub {
Text::Xslate->print(
Text::Xslate::mark_raw('<span style="color: red; font-size: 1.8em;">'),
"FILL ME/$base_key$_[0]",
Text::Xslate::mark_raw('</span>')
);
return undef;
}
);
}
{
my $vars_ref = hash_with_default_walker('', hash => +{ foo => +{ a => 1 } });
my $tx = Text::Xslate->new();
print $tx->render_string(<<'T', $vars_ref);
Hello, <: if ($oops) { :>sursen<: } :> world!
Hello, <: if ($hash.foo.a) { :>sursen<: } :> world!
Hello, <: if ($hash.foo.b) { :>sursen<: } :> world!
T
# => Hello, <span style="color: red; font-size: 1.8em;">FILL ME/oops</span> world!
# => Hello, sursen world!
# => Hello, <span style="color: red; font-size: 1.8em;">FILL ME/hash.foo.b</span> world!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment