Use tags like {{ variable }}
or {% include header.html %} or
{% block items %}{{ item }}{% endblock %}` in your template files.
Load the templates with NLTemplate, fill in the variables and setup the
repeating blocks with C++ code and render the result to stdout or
into a string.
- Variable replacement
- Repeatable or optional blocks
- File includes
- No external dependencies
- C++11 (please use the C++98 branch if you need support for legacy compilers)
To start using NLTemplate, add NLTemplate.cpp to your project and make sure NLTemplate.h is in your header search path.
If you use Xcode, just open and run the demo project. On the command line, you could run the demo like this:
git clone git@github.com:catnapgames/NLTemplate.git
cd NLTemplate/NLTemplate
gcc -Wall -pedantic -o demo -lstdc++ *.cpp
./demo
#include <iostream>
#include "NLTemplate.h"
using namespace std;
using namespace NL::Template;
int main(int, char *[] ) {
const char *titles[ 3 ] = { "Chico", "Harpo", "Groucho" };
const char *details[ 3 ] = { "Red", "Green", "Blue" };
LoaderFile loader; // Let's use the default loader that loads files from disk.
Template t( loader );
t.load( "test.txt" ); // Load & parse the main template and its dependencies.
t.set( "text", "Hello, world" ); // Set a top-level variable
t.block( "items" ).repeat( 3 ); // We need to know in advance that the "items" block will repeat 3 times.
// Let's fill in the data for the repeated block.
for ( int i=0; i < 3; i++ ) {
// Set title and text by accessing the variable directly
t.block( "items" )[ i ].set( "title", titles[ i ] );
t.block( "items" )[ i ].set( "text", "Lorem Ipsum" );
// We can get a shortcut reference to a nested block
Block & block = t.block( "items" )[ i ].block( "detailblock" );
block.set( "detail", details[ i ] );
// Disable this block for the first item in the list. Can be useful for opening/closing HTML tables etc.
if ( i==0 ) {
block.disable();
}
}
t.render( cout ); // Render the template with the variables we've set above
return 0;
}
{% include header.txt %}
<p>Items:</p>
{% block items %}<p>
Title: {{ title }}<br/>
Text: {{ text }}<br/>
{% block details %}Detail: {{ detail }}{% endblock %}
</p>{% endblock %}
<html><body>
<h1>{{ text }}</h1>
Despite the headline, there is nothing HTML-specific in NLTemplate. You can use XML, JSON or plain text as well for your templates.
If you use NLTemplate in a project, I'd love to hear about it. Please do let me know at tom@catnapgames.com. Thanks!
Goes well with NLDatabase - a lightweight SQLite wrapper for C++.