|
1 | 1 | from typing import Dict |
2 | 2 |
|
3 | 3 | from django import template |
| 4 | +from django.template.base import Node |
| 5 | +from django.template.exceptions import TemplateSyntaxError |
| 6 | +from django.template.loader_tags import construct_relative_path |
4 | 7 | from django.utils.safestring import SafeString |
5 | 8 |
|
6 | | -from coltrane.renderer import get_html_and_markdown |
| 9 | +from coltrane.renderer import ( |
| 10 | + get_html_and_markdown, |
| 11 | + render_html_with_django, |
| 12 | + render_markdown_path, |
| 13 | +) |
7 | 14 | from coltrane.retriever import get_content_directory, get_content_paths |
8 | 15 |
|
9 | 16 |
|
@@ -45,3 +52,58 @@ def directory_contents(context, directory: str = None) -> Dict[str, str]: |
45 | 52 | contents.append(metadata) |
46 | 53 |
|
47 | 54 | return contents |
| 55 | + |
| 56 | + |
| 57 | +class IncludeMarkdownNode(Node): |
| 58 | + """ |
| 59 | + Based on: `django.template.loader_tags.IncludeNode`. |
| 60 | + """ |
| 61 | + |
| 62 | + context_key = "__include_markdown_context" |
| 63 | + |
| 64 | + def __init__(self, template, *args, **kwargs): |
| 65 | + self.template = template |
| 66 | + super().__init__(*args, **kwargs) |
| 67 | + |
| 68 | + def render(self, context): |
| 69 | + """ |
| 70 | + Render the specified template and context. |
| 71 | + """ |
| 72 | + |
| 73 | + template_name = self.template.resolve(context) |
| 74 | + |
| 75 | + cache = context.render_context.dicts[0].setdefault(self, {}) |
| 76 | + template = cache.get(template_name) |
| 77 | + |
| 78 | + if template is None: |
| 79 | + template = context.template.engine.select_template((template_name,)) |
| 80 | + cache[template_name] = template |
| 81 | + |
| 82 | + (html, metadata) = render_markdown_path(template.origin.name) |
| 83 | + |
| 84 | + return render_html_with_django(html, metadata) |
| 85 | + |
| 86 | + |
| 87 | +@register.tag("include_md") |
| 88 | +def do_include_md(parser, token): |
| 89 | + """ |
| 90 | + Load a markdown template and render it with the current context. |
| 91 | +
|
| 92 | + Based on: `django.template.loader_tags.do_include`. |
| 93 | +
|
| 94 | + Example: |
| 95 | + {% include "foo/some_include" %} |
| 96 | + """ |
| 97 | + bits = token.split_contents() |
| 98 | + |
| 99 | + if len(bits) < 2: |
| 100 | + raise TemplateSyntaxError( |
| 101 | + "%r tag takes at least one argument: the name of the template to " |
| 102 | + "be included." % bits[0] |
| 103 | + ) |
| 104 | + |
| 105 | + bits[1] = construct_relative_path(parser.origin.template_name, bits[1]) |
| 106 | + |
| 107 | + return IncludeMarkdownNode( |
| 108 | + parser.compile_filter(bits[1]), |
| 109 | + ) |
0 commit comments