Random Template Rendering Sanic Web App

  • Share this:

Code introduction


This function creates a Sanic web application that uses Jinja2 templating engine to render a randomly selected HTML template and returns it in JSON format.


Technology Stack : Sanic, Jinja2, SanicJinja2

Code Type : Sanic Web Application

Code Difficulty : Intermediate


                
                    
import random
from sanic import Sanic
from sanic.response import json
from sanic_jinja2 import SanicJinja2

def random_sanic_function():
    # Create a Sanic app
    app = Sanic(name='RandomSanicApp')

    # Initialize Jinja2 with the app
    jinja = SanicJinja2(app, loader=FileSystemLoader('templates'))

    # Define a random function that uses Jinja2 templating and JSON response
    @app.route('/random', methods=['GET'])
    async def random_template(request):
        # Generate a random template name
        template_name = random.choice(['index.html', 'about.html', 'contact.html'])

        # Render the random template
        return await jinja.render_async(template_name, request=request)

    return app

# JSON output