Skip to content

3. Jinja Renderering

Yousef Z edited this page Jan 8, 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>
    <embed key="balance">
        <title>Hello {{player.name}}</title>
        <colour>cyan</colour>
        <fields>
            <field>
	        <title>Balance Remaining</title>
		<value>${{player.balance}}</value>
	    </field>
	</fields>
    </embed>
</discord>

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


🎇 Jinja Manager

To use the Jinja XML Renderer is simple, there are two ways of using it. The first way is to decorate the commands

from dataclasses import dataclass
from jinja2 import Environment, FileSystemLoader

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


@dataclass
class Player:
    name: str
    balance: float

@bot.command()
@qalib.qalib_context(Jinja2(), "templates/balance.xml")
def balance(ctx, name):
    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):
    manager = qalib.JinjaManager(ctx, qalib.Renderer(Jinja2(), "templates/balance.xml"))
    await ctx.rendered_send("balance", keywords={"player": Player(name, 1000.0)})
Clone this wiki locally