Dynamic directory trees templates¶
Directory trees can be computed from templates.
Thus you can use all features of template engines to render filenames, select templates or even alter context.
Use cases¶
While rendering a directory...
- skip some files based on variables ;
- render a single template several times with different output filenames ;
- alter template context data for some templates ;
- use loops, conditions... and all template-engine features...
The template tree template¶
When you POST to a directory, diecutter looks for special ”.diecutter-tree” template in that directory. If present, it renders ”.diecutter-tree” against context, decodes JSON, then iterates over items to actually render the directory.
Except when rendering a directory resource, ”.diecutter-tree” template is a normal template resource file. Manage it as any other template file.
Example¶
Let’s explain this feature with an example...
Create a “dynamic-greetings” directory resource, which contains only one “greetings.txt” template:
echo '{{ greeting }} {{ who }}!' | curl -X PUT -F "file=@-" http://localhost:8106/dynamic-greetings/greetings.txt
Let’s make “dynamic-greetings” directory dynamic, by putting a .diecutter-tree template:
echo '[
{% for greeting in greetings %}
{
"template": "greetings.txt",
"filename": "{{ greeting }}.txt",
"context": {"greeting": "{{ greeting }}"}
}{% if not loop.last %},{% endif %}
{% endfor %}
]
' | curl -X PUT -F "file=@-" http://localhost:8106/dynamic-greetings/.diecutter-tree
POST to .diecutter-tree returns a JSON-encoded list:
curl -X POST -d greetings=hello -d greetings=goodbye http://localhost:8106/dynamic-greetings/.diecutter-tree
[
{
"template": "greetings.txt",
"filename": "hello.txt",
"context": {"greeting": "hello"}
},
{
"template": "greetings.txt",
"filename": "goodbye.txt",
"context": {"greeting": "goodbye"}
}
]
JSON-encoded list items are dictionaries with the following keys:
- “template”: relative path to a template, i.e. content to be rendered ;
- “filename”: filename to return to the client ;
- “context”: optional dictionary of context overrides.
Now let’s render the directory as an archive:
$ curl -X POST \
-d name=Remy -d greetings=hello -d greetings=goodbye \
http://localhost:8106/dynamic-greetings \
| tar -zxv
$ tree dynamic-greetings
dynamic-greetings
├── hello.txt
└── goodbye.txt
0 directory, 2 files
$ cat hello.txt
hello Remy!
$ cat goodbye.txt
goodbye Remy!