Template Render Engine

Overview

Template Render Engine

Why TRender?

It is just another template render engine so why should one choose TRender? TRender was originally created for SiriDB which needed a fast and simple template engine.

  • Fast: TRender is able to render the SiriDB main page 1000x in 0.03 seconds.
  • Simple: Well, you have to decide for yourself if this is a good thing. TRender is not extensivery rich in its capabilities but still can include and extend templates, it has conditional statements, for loops and can use blocks and macros. The template language has some resemblance with Quik (another template engine) but is somewhat different.

Installation

The easiest way is to use PyPI:

sudo pip3 install trender

Quick usage

from trender import TRender

template = '@greet world!'
compiled = TRender(template)
output = compiled.render({'greet': 'Hello'})

print(output) # => Hello world! 

Basics

TRender uses a template as input. This template can be a string or filename. Some options like include and extend are only available when using a filename and template path. When initializing an instance of TRender it will compile the given template. Usually this will happen only once for each template. The TRender instance can then be rendered with a dictionary (we call this a namespace and we actually create a 'Namespace' instance from the given dictionary). TRender is optimized to render a compiled template very fast.

When using a filename we also need to specify a path, like:

TRender('base.template', path='path_to_file')

Note that path should be the root path for your templates. Assume we have the following path structure:

/templates/
/templates/pages/
		base.template
/templates/components/
		component.template

Then it is best to initialize TRender like TRender('pages/base.template', '/templates') so the engine will be able to find components/component.template when used inside your template.

Both #extend and #include are only available when using a template file, not with a simple string.

Using variable

Variable in a template are prefixed with an @ and optionally can be closed with an ! exclamation mark. A variable can only include alphabetic characters, digits and underscores. (And a ., but this has a special meaning to select nested variable). If you want to use a @ as a symbol in the template, add ! as an escape character.

Examples:

# Just render a simple variable...

TRender('@name is sweet').render({
	'name': 'Iris'
}) 
# Output => "Iris is sweet"
# Escape @ to render an email address...
	
TRender('@name@!@domain').render({
	'name': 'iris', 
	'domain': 'home.nl'
})
# Output => "[email protected]"
# Use nested variable (you can use nesting as deep as you want)...

TRender('@person.name is @person.age years old').render({
	'person': {
		'name': 'Iris', 
		'age': 4
	}
})
# Output => "Iris is 4 years old"
# Close variable when needed...

TRender('@name!IsSweet').render({
	'name': 'Iris'
})
# Output => "IrisIsSweet"

Comments

Comments should start with ## or a # followed by a space.

Example:

# This is a comment line
##This is a comment line too

Conditionals

Conditionals are very simple in TRender. We evaluate a simple value or allow a function for more complex conditionals. We start with #if followed by an optional #elif finally an optional #else and close with #end. If a conditional is not available in the namespace it will evaluate as false.

Simple example:

TRender('''

#if @sweet:
	I'm sweet
#elif @nice:
	I'm nice
#else:
	Don't know..
#end

''').render({'nice': True})

# Output => "I'm nice"

Complex example (actually it's not really complex...)

TRender('''

#if @old_enough(@person.age):
	I'm old enough
#else:
	I'm NOT old enough
#end

''').render({
	'old_enough': lambda age: age >= 18,
	'person': {'age': 37}
})

# Output => "I'm old enough"

Loops

We use #for loops and the loop should always close with #end.

Since an example explains more than words:

TRender('''

#for @person in @people:
	@person.name is @person.age years old
#end

''').render({
	'people': [
		{'name': 'Iris', 'age': 4},
		{'name': 'Sasha', 'age': 32}
	]
})

# Output =>
#	Iris is 4 years old
#	Sasha is 32 years old

Blocks

Sometimes you want to define a block and re-use this block several times. As a name convention I like to write blocks using CamelCase.

Example:

TRender('''

#block Item:
    
  • @item
  • #end
      #for @item in @items: #Item #end
    ''').render({ 'items': ['laptop', 'mouse'] }) # Output => #
      #
    • laptop
    • #
    • mouse
    • #

    Macros

    Macros are like blocks, except that they will be compiled only once using the namespace where the macro is defined. For example if we had used a macro in the block example above, we would get two empty

  • items since @item was not available when defining the macro. As a name convention I like to write macros using UPPERCASE_CHARACTERS.

    Include

    Including files is only possible when using a template file as source. Includes happen at compile time so they have no extra costs during rendering.

    Example:

    # base.template
    <h1>Let's include a fileh1>
    #include another.template
    <span>Yes, it worked!span>
    # another.template
    <span>Please, include me...span>
    # Now compile and render the templates
    TRender('base.template', '.').render()
    
    # Output =>
    #    

    Let's include a file

    # Please, include me... # Yes, it worked!

    Extend

    Extend can be used to extend a template. This is ofter useful when we want to use a base template but start rendering another specific template. It's only possible to use extend when using a template file as source.

    Example:

    # base.template
    <html>
    <head>
    <title>I'm a base templatetitle>
    head>
    <body>
    #CONTENT
    body>
    html>
    # some.template
    #extend base.template:
    
    #macro CONTENT:
    <span>This is just some content...span>
    #end 
    
    #end 
    # Now compile and render the templates
    TRender('some.template', '.').render()
    
    # Output =>
    #    
    #    
    #    I'm a base template
    #    
    #    
    #    This is just some content...
    #    
    #    

    How to use TRender with aiohttp (web server)

    TRender can used together with the aiohttp web server by using simple decorators for loading and rendering templates.

    Example:

    from trender.aiohttp_template import setup_template_loader
    from trender.aiohttp_template import template
    
    # The 'template' decorator can be used to load a template.
    # we assume in this example that you have the following template:
    #
    #   /my_template_path/base.template
    #
    # and you want to render this using the namespace:
    #
    #   {'name': 'Iris'}
    
    @template('base.template')
    async def myhandler(request):
        return {'name': 'Iris'}
    
    # This will setup the template loader. Make sure you run this only once, 
    # after template decorators are initialized.
    setup_template_loader('/my_template_path')
    
    	
    # Thats it!
    You might also like...
    Discord.py-Bot-Template - Discord Bot Template with Python 3.x

    Discord Bot Template with Python 3.x This is a template for creating a custom Di

    Streamlit-template - A streamlit app template based on streamlit-option-menu
    Streamlit-template - A streamlit app template based on streamlit-option-menu

    streamlit-template A streamlit app template for geospatial applications based on

    Pincer-bot-template - A template for a Discord bot created using the Pincer library

    Pincer Discord Bot Template (Python) WARNING: Pincer is still in its alpha/plann

    Fastapi-ml-template - Fastapi ml template with python

    FastAPI ML Template Run Web API Local $ sh run.sh # poetry run uvicorn app.mai

    Flask-template - A simple template for make an flask api

    flask-template By GaGoU :3 a simple template for make an flask api notes: you ca

    ✈️ HTML Template engine for python. Supports XSS preventation and many more!

    Htmotor HTML Template Engine for Python! Installation: Open your terminal and type pip install htmotor.

    LinkML based SPARQL template library and execution engine

    sparqlfun LinkML based SPARQL template library and execution engine modularized core library of SPARQL templates generic templates using common vocabs

    The best way to have DRY Django forms. The app provides a tag and filter that lets you quickly render forms in a div format while providing an enormous amount of capability to configure and control the rendered HTML.
    The best way to have DRY Django forms. The app provides a tag and filter that lets you quickly render forms in a div format while providing an enormous amount of capability to configure and control the rendered HTML.

    django-crispy-forms The best way to have Django DRY forms. Build programmatic reusable layouts out of components, having full control of the rendered

    Simple plotting for Python. Python wrapper for D3xter - render charts in the browser with simple Python syntax.
    Simple plotting for Python. Python wrapper for D3xter - render charts in the browser with simple Python syntax.

    PyDexter Simple plotting for Python. Python wrapper for D3xter - render charts in the browser with simple Python syntax. Setup $ pip install PyDexter

    Quickly and accurately render even the largest data.
    Quickly and accurately render even the largest data.

    Turn even the largest data into images, accurately Build Status Coverage Latest dev release Latest release Docs Support What is it? Datashader is a da

    Quickly and accurately render even the largest data.
    Quickly and accurately render even the largest data.

    Turn even the largest data into images, accurately Build Status Coverage Latest dev release Latest release Docs Support What is it? Datashader is a da

    Render reMarkable documents to PDF
    Render reMarkable documents to PDF

    rmrl: reMarkable Rendering Library rmrl is a Python library for rendering reMarkable documents to PDF files. It takes the original PDF document and th

    Render Jupyter notebook in the terminal
    Render Jupyter notebook in the terminal

    jut - JUpyter notebook Terminal viewer. The command line tool view the IPython/Jupyter notebook in the terminal. Install pip install jut Usage $jut --

    Code for
    Code for "Single-view robot pose and joint angle estimation via render & compare", CVPR 2021 (Oral).

    Single-view robot pose and joint angle estimation via render & compare Yann Labbé, Justin Carpentier, Mathieu Aubry, Josef Sivic CVPR: Conference on C

    Official code for
    Official code for "End-to-End Optimization of Scene Layout" -- including VAE, Diff Render, SPADE for colorization (CVPR 2020 Oral)

    End-to-End Optimization of Scene Layout Code release for: End-to-End Optimization of Scene Layout CVPR 2020 (Oral) Project site, Bibtex For help conta

    The best way to have DRY Django forms. The app provides a tag and filter that lets you quickly render forms in a div format while providing an enormous amount of capability to configure and control the rendered HTML.
    The best way to have DRY Django forms. The app provides a tag and filter that lets you quickly render forms in a div format while providing an enormous amount of capability to configure and control the rendered HTML.

    django-crispy-forms The best way to have Django DRY forms. Build programmatic reusable layouts out of components, having full control of the rendered

    render sprites into your desktop environment as shaped windows using GTK

    spritegtk render static or animated sprites into your desktop environment as dynamic shaped windows using GTK requires pycairo and PYGobject: pip inst

    goal: render videos on eu4's timeline function
    goal: render videos on eu4's timeline function

    Rendering Videos on the EU4 Time Line This repository contains code to create an eu4-savefile that plays back a video in question.

    The best way to have DRY Django forms. The app provides a tag and filter that lets you quickly render forms in a div format while providing an enormous amount of capability to configure and control the rendered HTML.
    The best way to have DRY Django forms. The app provides a tag and filter that lets you quickly render forms in a div format while providing an enormous amount of capability to configure and control the rendered HTML.

    django-crispy-forms The best way to have Django DRY forms. Build programmatic reusable layouts out of components, having full control of the rendered

    Comments
    • aiohttp template decorator not working when a handler function is used.

      aiohttp template decorator not working when a handler function is used.

      The current template decorator need a handler to be written from a class.

      example:

      class Handlers:
      
          @template('base.template')
          async def myhandler(self, request):
             return {'name': 'Test'}
      

      but the following does not work:

      @template('base.template')
      async def myhandler(self, request):
         return {'name': 'Test'}
      
      bug 
      opened by joente 2
    • Fix typo in an example from README.md

      Fix typo in an example from README.md

      The change fixes a typo in python's True value name, which appers to be lower-case in an example from README.md. This avoids a runtime issue while trying to execute the example code snippet:

      NameError: name 'true' is not defined

      Signed-off-by: Vladimir Zapolskiy [email protected]

      opened by vzapolskiy 1
    • pb rendering html page with style

      pb rendering html page with style

      Try tout use on micropython ma n'y tanks for this projet with no dépencies
      If i Try tout use with html pages with style on # or @keyframe generate an error

      opened by sophiedegran 0
    Releases(1.0.10)
    Owner
    Cesbit
    Building cloud enabled and open source software solutions.
    Cesbit
    Simple reuse of partial HTML page templates in the Jinja template language for Python web frameworks.

    Jinja Partials Simple reuse of partial HTML page templates in the Jinja template language for Python web frameworks. (There is also a Pyramid/Chameleo

    Michael Kennedy 106 Dec 28, 2022
    HTML Template Linter and Formatter. Use with Django, Jinja, Nunjucks and Handlebars templates.

    Find common formatting issues and reformat HTML templates. Django · Jinja · Nunjucks · Handlebars · Mustache · GoLang Ps, --check it out on other temp

    Riverside Healthcare Analytics 263 Jan 1, 2023
    A general purpose template driven code generator

    ?? Shit Mountain Generator A general purpose template driven code generator Contribute shits to your company's shit mountain more efficiently! Quick S

    Kelly 14 Mar 9, 2022
    A string template language hosted by Python3 runtime

    A string template language hosted by Python3 runtime. Conventionally, the source code of this language is written in plain text with utf-8 encoding and stored in a file with extension ".meme".

    null 6 Nov 2, 2022
    A simple, elegant Python based web templating engine (part of web.py).

    Templator Simple, elegant Python based web templating (part of web.py). If you are familiar with Python, there is no new syntax to learn. This is a st

    Dan 1 Dec 13, 2021
    An unofficial Blender add-on for Autodesk's Arnold render engine.

    Arnold for Blender Arnold for Blender (or BtoA) provides a bridge to the Arnold renderer from within Blender's standard interface. BtoA is an unoffici

    Luna Digital, Ltd. 89 Dec 28, 2022
    Flask Project Template A full feature Flask project template.

    Flask Project Template A full feature Flask project template. See also Python-Project-Template for a lean, low dependency Python app. HOW TO USE THIS

    Bruno Rocha 96 Dec 23, 2022
    Template for a Dataflow Flex Template in Python

    Dataflow Flex Template in Python This repository contains a template for a Dataflow Flex Template written in Python that can easily be used to build D

    STOIX 5 Apr 28, 2022
    This project uses Template Matching technique for object detecting by detection of template image over base image.

    Object Detection Project Using OpenCV This project uses Template Matching technique for object detecting by detection the template image over base ima

    Pratham Bhatnagar 7 May 29, 2022
    This project uses Template Matching technique for object detecting by detection of template image over base image

    Object Detection Project Using OpenCV This project uses Template Matching technique for object detecting by detection the template image over base ima

    Pratham Bhatnagar 4 Nov 16, 2021