tethysplatform / tethys

The Tethys Platform main Django website project repository.
http://tethysplatform.org/
BSD 2-Clause "Simplified" License
92 stars 49 forks source link

[FEATURE] render method on app #997

Closed sdc50 closed 4 months ago

sdc50 commented 9 months ago

Currently controllers render html doing something like this:

from django.shortcuts import render

@controller
def home(request):
    ...
    return render(request, 'app_package/home.html', context)

This is a simple/minor change, but could prevent issues especially for those doing the tutorials and decide to give their name a different name.

from .app import MyApp as app

@controller
def home(request):
    ...
    return app.render(request, 'home.html', context)

In app.py it would be a simple implementation:

from django.shortcuts import render

def render(self, request, template, context):
    return render(request, f'{self.package}/{template}', context)

We could also add some additional shortcuts for other commonly used things like redirect, and maybe a url template tag provided by the app (or that accepts the app as an argument). The point is to just prevent using the app.package as a magic string that can be error prone.

swainn commented 9 months ago

This is an excellent idea. Would give us a place to insert some additional logic in the future too. +1

sdc50 commented 5 months ago

I couldn't figure out a good way to create a template tag from a class method, but since the tethys_app object is passed to the template context anyway, it was pretty easy to just add the package to that object. I created a custom filter that appends the app package with the controller name. This is how it would be used:

<a href="{% url tethys_app|url:'my_controller' %}">My Page</a>
sdc50 commented 5 months ago

I also made a similar public url:

<link href="{% static tethys_app|public:'vendor/prism/prism.min.css' %}" rel="stylesheet"/>

Unfortunately, I don't think there is a way to do something similar for the extends tag. That one will have to have the hard-coded app.package.

sdc50 commented 5 months ago

I found an approach for not using the app.package in the extends tag.

{% extends tethys_app.package|add:"/base.html" %}