Basic template system

The recommended usage of this framework is to define specific subclasses of Template to provide structural elements on the final document

Introduced classes

class Template

template :: Template

Templates are simple hierarchical pieces of text used for efficient stream writing.

All class definitions

class Template

template $ Template

Templates are simple hierarchical pieces of text used for efficient stream writing.
package_diagram template::template template core core template::template->core gen_nit::gen_nit gen_nit gen_nit::gen_nit->template::template nitcorn::http_response http_response nitcorn::http_response->template::template html::bootstrap bootstrap html::bootstrap->template::template markdown::markdown markdown markdown::markdown->template::template markdown2::commonmark_gen commonmark_gen markdown2::commonmark_gen->template::template template::macro macro template::macro->template::template template::tmpl_composer tmpl_composer template::tmpl_composer->template::template gamnit::texture_atlas_parser texture_atlas_parser gamnit::texture_atlas_parser->gen_nit::gen_nit gamnit::texture_atlas_parser... ... gamnit::texture_atlas_parser...->gamnit::texture_atlas_parser nitcorn::reactor reactor nitcorn::reactor->nitcorn::http_response nitcorn::sessions sessions nitcorn::sessions->nitcorn::http_response nitcorn::http_errors http_errors nitcorn::http_errors->nitcorn::http_response nitcorn::reactor... ... nitcorn::reactor...->nitcorn::reactor nitcorn::sessions... ... nitcorn::sessions...->nitcorn::sessions nitcorn::http_errors... ... nitcorn::http_errors...->nitcorn::http_errors a_star-m a_star-m a_star-m->html::bootstrap a_star-m->markdown2::commonmark_gen a_star-m->template::tmpl_composer a_star-m... ... a_star-m...->a_star-m markdown::decorators decorators markdown::decorators->markdown::markdown markdown::man man markdown::man->markdown::markdown markdown::wikilinks wikilinks markdown::wikilinks->markdown::markdown markdown::decorators... ... markdown::decorators...->markdown::decorators markdown::man... ... markdown::man...->markdown::man markdown::wikilinks... ... markdown::wikilinks...->markdown::wikilinks popcorn::pop_templates pop_templates popcorn::pop_templates->template::macro popcorn::pop_templates... ... popcorn::pop_templates...->popcorn::pop_templates


module abstract_collection

core :: abstract_collection

Abstract collection classes and services.
module abstract_text

core :: abstract_text

Abstract class for manipulation of sequences of characters
module array

core :: array

This module introduces the standard array structure.
module bitset

core :: bitset

Services to handle BitSet
module bytes

core :: bytes

Services for byte streams and arrays
module circular_array

core :: circular_array

Efficient data structure to access both end of the sequence.
module codec_base

core :: codec_base

Base for codecs to use with streams
module codecs

core :: codecs

Group module for all codec-related manipulations
module collection

core :: collection

This module define several collection classes.
module environ

core :: environ

Access to the environment variables of the process
module error

core :: error

Standard error-management infrastructure.
module exec

core :: exec

Invocation and management of operating system sub-processes.
module file

core :: file

File manipulations (create, read, write, etc.)
module fixed_ints

core :: fixed_ints

Basic integers of fixed-precision
module fixed_ints_text

core :: fixed_ints_text

Text services to complement fixed_ints
module flat

core :: flat

All the array-based text representations
module gc

core :: gc

Access to the Nit internal garbage collection mechanism
module hash_collection

core :: hash_collection

Introduce HashMap and HashSet.
module iso8859_1

core :: iso8859_1

Codec for ISO8859-1 I/O
module kernel

core :: kernel

Most basic classes and methods.
module list

core :: list

This module handle double linked lists
module math

core :: math

Mathematical operations
module native

core :: native

Native structures for text and bytes
module numeric

core :: numeric

Advanced services for Numeric types
module protocol

core :: protocol

module queue

core :: queue

Queuing data structures and wrappers
module range

core :: range

Module for range of discrete objects.
module re

core :: re

Regular expression support for all services based on Pattern
module ropes

core :: ropes

Tree-based representation of a String.
module sorter

core :: sorter

This module contains classes used to compare things and sorts arrays.
module stream

core :: stream

Input and output streams of characters
module text

core :: text

All the classes and methods related to the manipulation of text entities
module time

core :: time

Management of time and dates
module union_find

core :: union_find

union–find algorithm using an efficient disjoint-set data structure
module utf8

core :: utf8

Codec for UTF-8 I/O


module core

core :: core

Standard classes and methods used by default by Nit programs and libraries.


module bootstrap

html :: bootstrap

HTML templates for Bootstrap components.
module commonmark_gen

markdown2 :: commonmark_gen

Generate Nitunit tests from commonmark specification.
module gen_nit

gen_nit :: gen_nit

Support to generate and otherwise manipulate Nit code
module http_response

nitcorn :: http_response

Provides the HttpResponse class and http_status_codes
module macro

template :: macro

String templating using macros.
module markdown

markdown :: markdown

Markdown parsing.


module a_star-m


module decorators

markdown :: decorators

Decorators for markdown parsing.
module example_angular

popcorn :: example_angular

This is an example of how to use angular.js with popcorn
module file_server

nitcorn :: file_server

Provides the FileServer action, which is a standard and minimal file server
module hooks

github :: hooks

Github hook event listening with nitcorn.
module htcpcp_server

nitcorn :: htcpcp_server

A server that implements HTCPCP. At the moment there are no additions.
module http_errors

nitcorn :: http_errors

Offers ErrorTemplate to display error pages
module loader

github :: loader

module log

nitcorn :: log

Services inserting a timestamp in all prints and to log each requests
module man

markdown :: man

Simple groff decorator restricted for manpages.
module nitcorn

nitcorn :: nitcorn

The nitcorn Web server framework creates server-side Web apps in Nit
module nitcorn_hello_world

nitcorn :: nitcorn_hello_world

Hello World Web server example
module nitcorn_reverse_proxy

nitcorn :: nitcorn_reverse_proxy

Minimal example using a ProxyAction
module nitmd

markdown :: nitmd

A Markdown parser for Nit.
module pop_auth

popcorn :: pop_auth

Authentification handlers.
module pop_handlers

popcorn :: pop_handlers

Route handlers.
module pop_json

popcorn :: pop_json

Introduce useful services for JSON REST API handlers.
module pop_routes

popcorn :: pop_routes

Internal routes representation.
module pop_sessions

popcorn :: pop_sessions

Session handlers
module pop_tasks

popcorn :: pop_tasks

Popcorn threaded tasks
module pop_templates

popcorn :: pop_templates

Template rendering for popcorn
module pop_tests

popcorn :: pop_tests

Popcorn testing services
module popcorn

popcorn :: popcorn

Application server abstraction on top of nitcorn.
module proxy

nitcorn :: proxy

Provides the ProxyAction action, which redirects requests to another interface
module pthreads

nitcorn :: pthreads

Activate the use of pthreads with nitcorn
module reactor

nitcorn :: reactor

Core of the nitcorn project, provides HttpFactory and Action
module restful

nitcorn :: restful

Support module for the nitrestful tool and the restful annotation
module restful_annot

nitcorn :: restful_annot

Example for the restful annotation documented at lib/nitcorn/restful.nit
module sessions

nitcorn :: sessions

Automated session management
module signal_handler

nitcorn :: signal_handler

Handle SIGINT and SIGTERM to close the server after all active events
module simple_file_server

nitcorn :: simple_file_server

Basic file server on port 80 by default, may require root to execute
module texture_atlas_parser

gamnit :: texture_atlas_parser

Tool to parse XML texture atlas and generated Nit code to access subtextures
# Basic template system
# The recommended usage of this framework is to define specific subclasses of
# Template to provide structural elements on the final document
module template

# Templates are simple hierarchical pieces of text used for efficient stream writing.
# # Efficient stream writing
# Templates are more efficient than ever-growing buffers with useless concatenation
# and more usable and maintainable than manual arrays of strings.
# The `add` method (and its variations) is used to append new content (like string or
# other templates) to a template object.
# Eventually, the `write_to` method (and its variations) is used to write the complete
# content of a template in streams (and files, and strings).
#     var tmpl = new Template
#     tmpl.add("A")
#     tmpl.add("B")
#     tmpl.add("C")
#     assert tmpl.write_to_string == "ABC"
# # Non-linear system with sub-templates.
# A template is made of a mix of string, sub-templates and other `Writable` objects.
# A sub-template can be constructed independently of its usages, thus simplifying
# the high-level logic.
# A single sub-template can be used more than once.
#     var main = new Template
#     var sub = new Template
#     sub.add("1")
#     main.add("A")
#     main.add(sub)
#     main.add("B")
#     main.add(sub)
#     main.add("C")
#     sub.add("2")
#     assert main.write_to_string == "A12B12C"
# See also the `new_sub` method.
# # Specific high-level templates
# The advanced, and recommended way, is to subclass Template and provide an autonomous
# structural template with its specific attributes and templating logic.
# In such a subclass, the full logic is provided by the `rendering` method that will
# be automatically and lazily invoked.
#     class LnkTmpl
#         super Template
#         var text: Writable
#         var title: nullable String
#         var href: String
#         redef fun rendering do
#             add """<a href="{{{href.html_escape}}}""""
#             if title != null then add """ title="{{{title.html_escape}}}""""
#             add ">"
#             add text
#             add "</a>"
#         end
#         # ...
#     end
#     var l = new LnkTmpl("hello world", null, "hello.png")
#     assert l.write_to_string == """<a href="hello.png">hello world</a>"""
class Template
	super Writable

	# Service used to render the content of the template.
	# Do nothing by default but subclasses should put all their specific
	# templating code in this method to regroup and simplify their logic
	# Note: to avoid inconsistencies, the template is automatically frozen
	# (see `freeze`) after the invocation of `rendering`.
	protected fun rendering do end

	# Append an element (`String`, other `Template`, etc.) at the end of the template.
	# Should be either used externally to act on basic templates,
	# or internally in the `rendering` method of specific templates.
	# Mixing the internal and external uses should be avoided because
	# the final behavior will depend on the lazy invocation of `rendering`.
	#     var t = new Template
	#     t.add("1")
	#     t.add("2")
	#     assert t.write_to_string == "12"
	fun add(element: Writable) do
		assert not is_frozen
		content.add element

	# Append `element` and the end of the template then append a "\n".
	#     var t = new Template
	#     t.addn("1")
	#     t.addn("2")
	#     assert t.write_to_string == "1\n2\n"
	fun addn(element: Writable) do
		add element
		add "\n"

	# Append a bunch of elements at the end of the template.
	# See `add`.
	#     var t = new Template
	#     t.add_all(["1", "2"])
	#     assert t.write_to_string == "12"
	fun add_all(elements: Collection[Writable]) do content.add_all elements

	# Append a bunch of elements at the end of the template with separations.
	# see `add`.
	#     var t = new Template
	#     t.add_list(["1", "2", "3"], ", ", " and ")
	#     assert t.write_to_string == "1, 2 and 3"
	fun add_list(elements: Collection[Writable], sep, last_sep: Writable) do
		var last = elements.length - 2
		var i = 0
		for e in elements do
			content.add e
			if i < last then
				content.add sep
			else if i == last then
				content.add last_sep
			i += 1

	# Is the template allowing more modification (`add`)
	var is_frozen = false

	# Disable further modification: no more `add` is allowed
	fun freeze
		if is_frozen then return
		is_frozen = true

	# Return a new basic template that is automatically added in `self` (using `add`)
	# This is an easy way to provide a free insertion point in an existing template.
	#     var t = new Template
	#     t.add("""void main(void) {""")
	#     var tdecl = t.new_sub # used to group declarations
	#     tdecl.add("int i; ")
	#     t.add("i = 1; ")
	#     tdecl.add("int j; ")
	#     t.add("j = i + 1; ")
	#     t.add("\}")
	#     assert t.write_to_string == """void main(void) {int i; int j; i = 1; j = i + 1; }"""
	fun new_sub: Template
		var res = new Template
		add res
		return res

	# Each sub-elements
	private var content = new Array[Writable]

	# Flag to avoid multiple rendering
	private var render_done = false

	# Call rendering, if not already done
	# Then freeze the template
	# This method is only required in corner-cases since
	# `rendering` is automatically called when needed.
	fun force_render
		if render_done then return
		render_done = true

	# Do the full rendering and write the final content to a stream
	redef fun write_to(stream)
		assert not is_writing
		is_writing = true
		for e in content do
		is_writing = false

	# Flag to avoid infinite recursivity if a template contains itself
	private var is_writing = false