Skip to content

3. Jinja Renderering

Yousef Z edited this page Apr 19, 2023 · 9 revisions

⛩️ Jinja

Jinja2's documentation is pretty extensive, and is capabilities are wide. This is why we gave the option to leverage Jinja. You can checkout Jinja2 here.

An example of a XML file using Jinja (that we are going to use for the next section) is

<discord>
    <message key="balance">
        <embed>
            <title>Hello {{player.name}}</title>
            <colour>cyan</colour>
            <fields>
                <field>
	            <title>Balance Remaining</title>
		    <value>${{player.balance}}</value>
        	</field>
            </fields>
        </embed>
    </message>
</discord>

This file was stored in the ~/templates/ directory as "balance.xml"


🎇 Using Jinja2 in a Renderer

To use the Jinja Template Engine usage here is simple, there are two ways of using it. The first way is to decorate the commands

from dataclasses import dataclass
from typing import Literal

from jinja2 import Environment, FileSystemLoader

from discord.ext import commands

import qalib
from qalib.template_engines.jinja2 import Jinja2


bot = commands.AutoShardedBot(command_prefix="!", intents=discord.Intents.all())
Messages = Literal["balance"]

@dataclass
class Player:
    name: str
    balance: float

@bot.command()
@qalib.qalib_context(Jinja2(), "templates/balance.xml")
def balance(ctx: qalib.QalibContext[Messages], name: str):
    await ctx.rendered_send("balance", keywords={"player": Player(name, 1000.0)})

There is also the manual way of instantiating the Jinja Manager

from dataclasses import dataclass
from jinja import Environment

import discord.ext.commands
import qalib
from qalib.template_engines.jinja2 import Jinja2


@dataclass
class Player:
    name: str
    balance: float


@bot.command()
def balance(ctx, name):
    context: qalib.QalibContext[Messages] = qalib.QalibContext(ctx, qalib.Renderer(Jinja2(), "templates/balance.xml"))

    await context.rendered_send("balance", keywords={"player": Player(name, 1000.0)})
Clone this wiki locally