Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 3557c28cdd
Fetching contributors…

Cannot retrieve contributors at this time

file 449 lines (346 sloc) 10.51 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
=head1 NAME

Garden - A functional template language

=head1 DESCRIPTION

A Perl 5 implementation of the Garden template language.
See https://github.com/supernovus/garden-spec/ for the specification.

=head1 USAGE

In ./templates/exampleTemplate.tmpl:

exampleTemplate (name) {{
Hello [[name]]
}}

In your Perl 5 script:

use Garden;
my $garden = Garden->new(paths=>['./templates']);
my $template = $garden->get('templateName');
say $template->render(name=>"World");

Returns:

Hello World

See the tests in the ./t/ folder and the specification for more details.

=cut

package Garden;

use Modern::Perl;
use Carp;

use Garden::Namespace;

our $VERSION = 1.1;

## The following will be set to a string representing a development
## release, if we are not yet a stable release. It will be set to
## 0 if this is a stable release.
our $DEVEL = 0;

use constant MIN_SPEC => 1; ## The lowest version of the spec we can parse.
use constant MAX_SPEC => 1; ## The highest version of the spec we can parse.

#use Huri::Debug show => ['all'];

## I'm not documenting lines(). It's a private subroutine only.

sub lines {
  my $filename = shift;
  open (my $file, $filename);
  my @lines = <$file>;
  return @lines;
}

=head1 CLASS METHODS

=over 1

=item new()

Create a new Garden object. This can take several optional parameters:

paths Paths to look for templates in. []
extension The file extension for templates without a dot 'tmpl'
delimiters Delimiters for template expressions ['[[', ']]']
block Delimiters for a template block ['{{', '}}']
dictblock Delimiters for a dictionary block ['{[', ']}']
comment Delimiters for a comment block ['/*', '*/']
indirect Delimiters for indirect lookups [ '`', '`' ]
condition Start and separator for conditional statements [ '?', ';' ]
alias Marker for alias statements '='
note Prefix for a here-to-newline comment '##'
positional Prefix for positional parameters '*'
apply Symbol to apply a template ':'
negate Prefix to negate conditions '!'

The typical usage would be:

my $garden = Garden->new(paths=>['./templates']);

=cut

sub new {
  my ($class, %opts) = @_;
  my %self = (
    extension => 'tmpl', ## The file extension of templates.
    syntax => {
      delimiters => ['[[', ']]'],
      block => ['{{', '}}'],
      dictblock => ['{[', ']}'],
      json => ['{<', '>}'],
      comment => ['/*', '*/'],
      condition => [ '?', ';' ],
      indirect => [ '`', '`' ],
      note => '##',
      alias => '=',
      positional => '*',
      apply => ':',
      negate => '!',
    },
    paths => [], ## Paths we search for files in.
    namespaces => {}, ## Each file we load, represents a Namespace.
    plugins => {}, ## Plugins add additional functionality.
    globals => {}, ## Global variables, available anywhere.
    extensions => { ## Extensions we support.
      plugins => 1, ## We support the plugins extension.
      json => 1, ## We support the JSON extension.
      globals => 1, ## We support the Global variables extension.
    },
  );
  ## Now let's see if we've overridden any of them.
  for my $key (keys %self) {
    if (exists $opts{$key}) {
      $self{$key} = $opts{$key};
    }
  }
  for my $key (keys %{$self{syntax}}) {
    if (exists $opts{$key}) {
      $self{syntax}->{$key} = $opts{$key};
    }
  }
  ## Okay, now let's return our object.
  return bless \%self, $class;
}

=back

=head1 PUBLIC METHODS

=over 1

=item syntax

Returns the Hash reference representing the top-level syntax settings.

=cut

sub syntax {
  my ($self) = @_;
  return $self->{syntax};
}

=item paths

Returns an array of paths. If passed 1, it builds a full copy
of the paths before returning them.

=cut

sub paths {
  my ($self, $copy) = @_;
  my @paths;
  if ($copy) {
    for my $path (@{$self->{paths}}) {
      push(@paths, $path);
    }
  }
  else {
    @paths = @{$_[0]->{paths}};
  }
  return @paths;
}

=item plugins

Returns the list of global plugins.

=cut

sub plugins {
  my ($self) = @_;
  return $self->{plugins};
}

=item globals

Returns the list of global variables.

=cut

sub globals {
  my ($self) = @_;
  return $self->{globals};
}

=item extensions

Returns the list of extensions we support.
This returns a flat array, consisting of just the names.

=item extensions(1)

Returns the list of extensions we support.
This returns a hash reference, with the key being the name of the extension,
and the value being the version of that extension we support.

=cut

sub extensions {
  my ($self, $full) = @_;
  if ($full) {
    return $self->{extensions};
  }
  else {
    return keys %{$self->{extensions}};
  }
}

=item supports($extension)

Returns the version of an extension we support.
Will return false if we do not support the extension.

=cut

sub supports {
  my ($self, $extension) = @_;
  if (exists $self->{extensions}{$extension}) {
    return $self->{extensions}{$extension};
  }
}

=item addPath($path,...)

Add a path to look for templates in. The path will be added to the
top of the search list (so it will be looked in first.)

You can specify multiple paths if you want.

=cut

sub addPath {
  my $self = shift;
  for my $path (reverse @_) {
    unshift(@{$self->{paths}}, $path);
  }
}

=item appendPath($path,...)

Add a path to look for templates in. The path will be added to the
bottom of the search list (so it will be looked in after existing paths.)

You can specify multiple paths if you want.

=cut

sub appendPath {
  my $self = shift;
  for my $path (@_) {
    push(@{$self->{paths}}, $path);
  }
}

=item addPlugin(name=>$plugin, ...)

Adds a plugin (or plugins) that will be made available to all templates.
The name is what the template will call the plugin via.

The $plugin part can either be an object, a class name, or path to a
Perl file. addPlugin will figure out how to handle it.

=cut

sub load_plugin {
  my ($self, $plugin) = @_;
  if ($plugin !~ /\.p[ml]/) {
    $plugin .= '.pm';
  }
  $plugin =~ s|::|/|g;
  if (eval { require $plugin; 1; }) {
    return 1;
  }
  return 0;
}

sub addPlugin {
  my ($self, %plugins) = @_;
  for my $plug (keys %plugins) {
    next if exists $self->{plugins}->{$plug}; ## No redefining.
    my $plugin = $plugins{$plug};
    if (! ref $plugin) {
      $self->load_plugin($plugin);
      $plugin = $plugin->new(engine=>$self);
    }
    $self->{plugins}->{$plug} = $plugin;
  }
}

=item addGlobal($name, $value)

Add a global variable that will be available to any namespace/template.
Namespaces can declare they require specific global variables, using the
optional "global" statement.

=cut

sub addGlobal {
  my ($self, $name, $value) = @_;
  $self->{globals}->{$name} = $value;
}

## Add a namespace object to our cache.
## Currently, it's a simple wrapper, may do better checking in the future.
sub add_namespace {
  my ($self, $name, $object) = @_;
  $self->{namespaces}->{$name} = $object;
}

## Load a namespace, adds it to our cache.
sub load_namespace_file {
  my ($self, $file, $name) = @_;
  my @lines = lines($file);
  my $namespace = Garden::Namespace->new(engine=>$self, lines=>\@lines);
  $self->add_namespace($name, $namespace);
  return $namespace;
}

=item get($name)

Get a template. Pass it the name of the template you are looking for,
and it will find it and return it.

=cut

## We don't document the paths option, as it's not a part of the public API.
sub get {
  my ($self, $name, %opts) = @_;
  my @paths;
  if (exists $opts{paths}) {
    @paths = @{$opts{paths}};
  }
  else {
    @paths = $self->paths;
  }
  ## If the name starts or ends with a slash, remove it.
  $name =~ s/^\/+//g;
  $name =~ s/\/+$//g;
  ## Now, let's get the template name, and a possible namespace name.
  my $tname = $name;
  my $sname;
  if ($name =~ /\//) {
    my @parts = split(/\//, $name);
    $tname = pop(@parts);
    $sname = join('/', @parts);
  }

  ## First, see if the template is an existing namespace.
  if (exists $self->{namespaces}->{$name}) {
    my $template = $self->{namespaces}->{$name}->get($tname, only=>1);
    return $template if defined $template;
  }
  ## Next, see if we have a prefixed namespace in our cache.
  if (defined $sname && exists $self->{namespaces}->{$sname}) {
    my $template = $self->{namespaces}->{$sname}->get($tname, only=>1);
    return $template if defined $template;
  }
  ## Okay, now, lets see if we can find a template file.
  my $ext = $self->{extension};
  $ext =~ s/^\.//g;
  my $file = $name . '.' . $ext;
  my $sfile;
  if (defined $sname) {
    $sfile = $sname . '.' . $ext;
  }
  for my $path (@paths) {
    my $fpath = $path . '/' . $file;
    my $spath;
    if (defined $sfile) {
      $spath = $path . '/' . $sfile;
    }
    ##[all,get]= $fpath $spath
    if (-f $fpath) {
      my $namespace = $self->load_namespace_file($fpath, $tname);
      my $template = $namespace->get($tname, only=>1);
      return $template if defined $template;
    }
    elsif (defined $spath && -f $spath) {
      my $namespace = $self->load_namespace_file($spath, $sname);
      my $template = $namespace->get($tname, only=>1);
      return $template if defined $template;
    }
  }
  croak "Template '$name' was not found, cannot continue.";
}

## Get a namespace. Not a public API call, this is used by Namespace.
sub get_namespace {
  my ($self, $name, %opts) = @_;
  my @paths;
  if (exists $opts{paths}) {
    @paths = @{$opts{paths}};
  }
  else {
    @paths = $self->paths;
  }
  $name =~ s/^\/+//g;
  $name =~ s/\/+$//g;
  if (exists $self->{namespaces}->{$name}) {
    return $self->{namespaces}->{$name};
  }
  my $file = $name . '.' . $self->{extension};
  for my $path (@paths) {
    my $fpath = $path . '/' . $file;
    if (-f $fpath) {
      return $self->load_namespace_file($fpath, $name);
    }
  }
  croak "Namespace '$name' was not found, cannot continue.";
}

=back

=head1 DEPENDENCIES

=over 1

=item Modern::Perl

All of the libraries use Modern::Perl to enforce some sane defaults.

=item Test::More

Used for testing.

=item Test::Exception

Used for testing.

=back

=head1 AUTHOR

Timothy Totten <https://github.com/supernovus/>

=head1 LICENSE

Artistic License 2.0

=cut

## End of class.
1;
Something went wrong with that request. Please try again.