Package: pypage
PyPage is a document template engine for Python programmers with a
short learning curve.Why use PyPage?Easy to pick up. Syntax similar to Python’s.You need an eval-based template engine.PyPage supports Python 3.x and 2.7, and has been tested
(usingtest_cmd) on CPython and PyPy.What does it look like?Some fruits with the character `r` in their name:<ul>{% for fruit in ['Apple', 'Strawberry', 'Orange', 'Raspberry'] if 'r' in fruit %}<li>{{ fruit }}</li>{% endfor %}</ul>InstallationYou caninstallPyPage easily withpip:pip install pypageTry runningpypage-hto see the command-line options available.Table of ContentsEmbedding CodeInline Code TagsMultiline Code TagsExecution EnvironmentThe write functionBlock TagsConditional BlocksFor LoopsWhile Loopsdofirst LoopsLong LoopsCapture BlocksFiner DetailsInheritance (with inject and exists)The include functionCommentsComment TagsComment BlocksWhitespace & IndentationWhitespace RemovalAutomatic IndentationLicenseEmbedding CodeIn order to embed code in a document, you wrap Python code with{{and}}. The{{ ... }}constructs are calledcode tags. There
are two kinds of code tags:inlineandmultiline.Inline Code TagsInline code tags occur entirely on the same line, i.e. the closing}}appears on the same line as the opening{{. Here is an
example of an inline code tag:Thereare{{5+2}}daysinaweek.The above, when processed by PyPage, yields:There are 7 days in a week.The Pythonevalstatement is used to execute the code in an inline
code tag. The result of the expression evaluation is converted into a
string (withstr) and the code tag is replaced with it.Multiline Code TagsMultiline code tags span multiple lines. The presence of one or more
newline (\n) characters between the{{and}}distinguishes
it from an inline code tag. Here’s an example:{{x=5y=2write("There are",x+y,"days in a week.")}}The Pythonexecfunction is used to execute the code in a multiline
code tag.Why have distinct inline code tags? It’s easier to write{{x}}than
to write{{ write(x) }}. Many a time, all we need to do is inject
the value of a variable at a specific location in the document.Execution EnvironmentAll code is executed in a shared common environment. I.e., thelocalsandglobalspassed intoevalandexecis a single shared dictionary,
for all code tags in the same file.As such, a variable instantiated in a code tag at the
beginning of the document, will be available to all other code tags in
the document. When PyPage is invoked as library, an initial seed
environment consisting of a Python dictionary mapping variable names to
values, can be provided.The write functionAwritefunction similar to the Python 3’sprintfunction
is accessible from both kinds of code tags. It writes text into
the document that substitutes/replaces the code tag it’s used in.write(*object,sep=' ',end='\n')Objects passed to it are stringified withstr, concatenated together
withsep, and terminated withend. The outputs of multiple calls
towritein a code tag are concatenated together, and the resulting
final output is injected in place of the code tag.Ifwriteis called from an inline code tag, the result of evaluating
the expression (aNone, sincewritewill return aNone) is
ignored, and the output of thewritecall is used instead.Block TagsBlock tags simplify certain tasks that would otherwise be cumbersome and
ugly if done exclusively with code tags. One of the things it lets you
do is wrap part of your page in anif/else
conditional,
or afor/while
loop.Here’s an example of theforblock tag:{%foriinrange(10)%}Thesquareof{{i}}is{{i*i}}.{%%}A block tag begins with{% tag_name ... %}and ends with{% %}.
Optionally, the end{% %}can be of the form{% endtag_name %}(i.e. prepend thetag_namewithend), which in the above example
would be{% endfor %}).Conditional BlocksIt’s best to explain this with an example:Hey,{{importrandom# Randomly pick a greetinggreeting=random.randint(1,4)}}{%ifgreeting==1%}Hello{%elifgreeting==2%}Bonjour{%elifgreeting==3%}Hey{%else%}Hi{%%}When the above template is run, the resulting page will contain a
randomly chosen greeting. As is evident, PyPage syntax for if/elif/else
conditions closely mirrors Python’s. The terminal{% %}can be
replaced with an{% endif %}with no change in meaning (as with any
block tag).For LoopsLet’s start with a simple example:{%forvowelin['a','e','i','o','u']%}{{vowel}}{%%}This will print out the vowels with a space after every character.Now that’s an ordinary for loop. PyPage permits for loops that are more
expressive than traditional Python for loops, by leveraging Python’sgenerator expressions.Here’s an example of something that would be impossible to do in Python
(with a regular for loop):{%forxin[1,2,3]foryin['a','b','c']%}{{x}}~{{y}}{%%}The above loop would result in:1 ~ a
1 ~ b
1 ~ c
2 ~ a
2 ~ b
2 ~ c
3 ~ a
3 ~ b
3 ~ cInternally, PyPage morphs the expressionfor x in [1,2,3] for y in['a','b','c']into the generator
expression(x, y) for x in [1,2,3] for y in['a','b','c']. It
exposes the the loop variablesxandyby injecting them into
your namespace.Note:Injected loop variables replace variables with the same name for
the duration of the loop. After the loop, the old variables with the
identical names are restored (PyPage backs them up).While LoopsA while loops looks like{{% while condition %}} ... {{% %}, whereconditioncan be any Python expression. Here’s an example:{{i=10j=20}}Numbersfrom{{i}}to{{j}}:{%whilei<=j%}{{write(str(i))i+=1}}{%%}This would simply list the numbers from 10 to 20.dofirst Loops{%whiledofirstFalse%}That's all, folks!{%%}Adding adofirstright after thewhileand before the expression
ensures that the loop is runat least once, before the condition is
evaluated.Long LoopsIf a loop runsfor more than 2 seconds, PyPage stops executing it, and
writes an error message tostdoutsaying that the loop had been
terminated. As PyPage is mostly intended to be used as a templating
language, loops generally shouldn’t be running for longer than two
seconds, and this timeout was added to make it easier to catch accidental
infinite loops. If you actually need a loop to run for longer than 2
seconds, you can add the keywordslowright after the condition expression
({{% while condition slow %}}), and that would suppress this 2-second timeout.Capture BlocksYou can capture the output of part of your page using thecapturetag:{%capturex%}hello{{"bob"}}{%%}The above tag will not yield any output, but rather a new variablexwill be created that captures the output of everything enclosed by it
(which in this case is"hello bob").Finer DetailsInheritance (with inject and exists)The approach taken by PyPage toward template inheritance is quite distinct from that of other
templating engines (like Jinja’s).
It’s a lot simpler. You call a PyPage-provided functioninjectwith the path of aPyPage templateyou want
to inject (i.e. “extend” in Jinja parlance), and PyPage will process that template under the current scope (with all
previously defined variables being available to the injected template), and theinjectfunction will return its output.A base template could look like this:<html><head><title>{% if exists('title') %}
        {{ title }}
        {% else %}
        No title
        {% %}</title></head><body>{{ body }}</body></html>A derived templates only needs to definebodyand optionallytitle, to “extend” the template above.{% capture body %}
The HTML body content would go in here.
{% %}
{{ inject('...path to the base template...') }}We didn’t specify atitleabove, but if we wanted to, we’d just need to make sure it was defined beforeinjectwas called. The base template checks whether atitlevariable exists by calling the functionexists. As is obvious,
theexistsfunction simply takes a variable name as a string, and returns a boolean indicating whether the variable
exists in the scope.This approach to inheritance is explicit and easy-to-grasp. Rather than have complex inheritance rules, with a default
block definition that is optionally overridden by a derived template, we make things more explicit by using conditionals
for cases where we want to provide a default/fallback definition. We error out if a definition is expected to be provided,
and is not present. The output of the “dervied” template is clear and obvious, with this approach.The include functionIf you want to include (as in, substitute) a file directly without processing it with PyPage, you can use theincludefunction. It functions like theinjectfunction, taking the path to a file as argument, and
returning the contents of the file unprocessed.CommentsComment TagsAnything bounded by{#and#}will be omitted from the output.
For example:<p>Lorem ipsum dolor sit amet
  {#<ul>Non sequitur</ul>#}
  consectetur adipisicing elit</p>Comment BlocksYou can also easily comment an existing block, by simply placing the wordcommentin front of it:<p>Lorem ipsum dolor sit amet
    {% comment for i in range(10) %}
        N = {{i}}
    {% %}
  consectetur adipisicing elit</p>Thecommentkeyword before theforabove results in the entire block
being commented out and omitted from the output.Whitespace & IndentationWhitespace RemovalIf a block tag is on a line by itself, surrounded only by whitespace,
then that whitespace is automatically excluded from the output. This
allows you indent your block tags without worrying about excess
whitespace in the generated document.Automatic IndentationPyPage smartly handles indentation for you. In a multi-line code tag, if
you consistently indent your Python code with a specific amount of
whitespace, that indentation will be stripped off before executing the
code block (as Python is indentation-sensitive), and the resulting
output of that code block will be re-indented with same whitespace that
the initial code block was.The whitespace preceding the second line of code determines the
peripheral indentation for the entiee block. All subsequent lines (after
second) must begin with exact same whitespace that preceded the second
line, or be an empty line.For example:<p>Lorem ipsum dolor sit amet<ul>{{
        def foo():
          write("Hello!")
        foo()
      }}</ul>consectetur adipisicing elit</p>would produce the following output:<p>Lorem ipsum dolor sit amet<ul>Hello!</ul>consectetur adipisicing elit</p>Note that theHello!was indented with same whitespace that the code
in the code block was.PyPage automatically intends the output of a multi-line tag to match the
indentation level of the code tag. The number of whitespace characters
at the beginning of the second line of the code block determines the
indentation level for the whole block. All lines of code following the
second line must at least have the same level of indentation as the
second line (or else, a PypageSyntaxError exception will be thrown).LicenseApache License Version
2.0