Share My Creation [WebApp] A Simple Html Template Parser

This is a mini template engine which can generate HTML dynamically by parsing templates on server-side. It is a bit like Django.

1. Templates
A template is a text file which contains variables, tags.

1.1 Variable
There are two types of template variables, one is common variable, the other is conditional variable.
TypeDecriptionUsage
CommonVariable name is put inside {{ }}<h1>Hello {{ firstname }}, how are you?</h1>
Conditional Variable name is put inside tags {%if isLogin %} or {% for menu in menus %}

1.2 Tags
Tags control the logic of the template. they are surrounded in {% %}. Some create text in the output, some control flow by performing loops or logic, and some load external information into the template to be used by later variables.
TagDecriptionUsage
blockDefine a section in a master template that should be replaced by a section in a child template{% block content %}{% endblock %}
if
[ else | elseif ]
endif
An if statement evaluates a boolean variable and executes a block of code if the value is true. {%if isLogin %}
<li class="nav-item"><a href="/logout" class="nav-link">LOGOUT</a></li>
{% else %}
<li class="nav-item"><a href="/login" class="nav-link">LOGIN</a></li>
{% endif %}
for inA for loop is used for iterating over a list. {% for menu in menus %}
<li class="nav-item"><a href={{menu.href}} class="nav-link {{ menu.active }}">{{menu.item}}</a></li>
{% endfor %}
extendsThe extends tag allows you to add a parent template for the current template.This means that you can have one master page that acts like a parent for all other pages{%extends base %}
{% block content %}
<h2>Page-{{uri}} {{username}}
</h2>{% endblock %}
includeThe include tag allows you to include a template inside the current template. This is useful when you have a block of content that is the same for many pages.{% include partial/header %}
body is content what you would like to do
{% include partial/footer %}

2. Use templates in B4J
The template parsing library b4jtpl.0.11.0 is attached.

2.1 Pass variables to templates
In B4J, template variables will are put into a map,each key of the map corresponds to a template variable name

2.2 initialize
HtmlTplParser is a class which generates HTML.
To use the class you need to set templatefile's basepath and extension

2.3 Render
A method render which returns html string by template file and map variale

For a hands-on example of creating HTML pages with templates, please see stplExample.

It's only a creation or a practice not a product, I did it just for learning b4x .
 

Attachments

  • stplExample.zip
    273.2 KB · Views: 147
  • b4jtpl.0.11.0.zip
    12.6 KB · Views: 133
  • 3.png
    3.png
    446 KB · Views: 1,764
  • 2.png
    2.png
    36.1 KB · Views: 184
  • 1.png
    1.png
    377.3 KB · Views: 180
Last edited:
Top