lasuillard / django-slack-tools

Little helpers working with Slack bot 🤖 in Django.
https://lasuillard.github.io/django-slack-tools/
MIT License
1 stars 0 forks source link

Django template support #15

Open lasuillard opened 8 months ago

lasuillard commented 8 months ago

Support Jinja for messaging policy to build payload more dynamically.

lasuillard commented 8 months ago

Alternative and preferred is, Django built-in: DTL.

lasuillard commented 8 months ago

Going to use Django built-in template engine. Renaming issue.

lasuillard commented 8 months ago

Example on how it would work (JSON5 is needed due to trailing commas):

import html
from pprint import pprint

import json5 as json
from django.template import Context, Template

template = Template(
    """
{
    "blocks": [
        {
            "type": "section",
            "fields": [
                {% spaceless %}
                {% for mention in mentions %}
                {
                    "type": "mrkdwn",
                    "text": "Hello, {{ mention }}"
                },
                {% endfor %}
                {% endspaceless %}
            ]
        },
    ]
}
""",
)

context = Context(
    {
        "mentions": ["<M1>", "<M2>"],
    },
)

json_str = template.render(context)
json_str = html.unescape(json_str)
obj = json.loads(json_str)

print(json_str)
pprint(obj)

Would show following result:

{
    "blocks": [
        {
            "type": "section",
            "fields": [
                {
                    "type": "mrkdwn",
                    "text": "Hello, <M1>"
                },

                {
                    "type": "mrkdwn",
                    "text": "Hello, <M2>"
                },
            ]
        },
    ]
}

{'blocks': [{'fields': [{'text': 'Hello, <M1>', 'type': 'mrkdwn'},
                        {'text': 'Hello, <M2>', 'type': 'mrkdwn'}],
             'type': 'section'}]}

Ref from https://stackoverflow.com/questions/2167269/load-template-from-a-string-instead-of-from-a-file.