Template context serialization #732
-
I'd love to be able to use ninja's router like this: class HomepageContext(Schema):
users: List[UserSchema]
@router.get(context: HomepageContext)
def homepage(request):
context = {"users": User.objects.all()}
return TemplateResponse(request, "homepage.html", context) MotivationMy use-case is Alpine.js, I'd like to pass all context data from Django to Alpine like so: // index.js
import Alpine from 'alpine.js';
Alpine.data('homepage', (contextData) => ({
context: null,
init() { this.context = contextData }
}); # homepage.html
<div x-data="homepage({{ context }})">...</div> Thus, I will be able to use Alpine.js directives without mixing them up with DTL. Serialized context can also be used with Riot.js (and maybe some other JS frameworks, who knows?). |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
What actauly happens when you call |
Beta Was this translation helpful? Give feedback.
-
what you need looks like this: @router.get('/')
def homepage(request):
return TemplateResponse(request, "homepage.html", {
'context': HomepageContext(users=User.objects.all()).json()
}) and add safe to template:
|
Beta Was this translation helpful? Give feedback.
@LazerRaptor
what you need looks like this:
and add safe to template: