Skip to content
This repository has been archived by the owner on Aug 18, 2022. It is now read-only.

Fix: ensure valid JSON string is generated in the data-page attr #8

Merged
merged 1 commit into from
May 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion django_inertia/templatetags/inertia_tags.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import json

from django import template
from django.utils.html import format_html
from django.utils.safestring import mark_safe
Expand All @@ -8,4 +10,6 @@
@register.simple_tag(takes_context=True)
def inertia(context, app_id="app"):
page = context["page__"]
return format_html('<div id="{}" data-page="{}"></div>', mark_safe(app_id), mark_safe(page))
return format_html(
"<div id=\"{}\" data-page='{}'></div>", mark_safe(app_id), mark_safe(json.dumps(page))
)
25 changes: 25 additions & 0 deletions tests/test_template_tag.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import json

from django.template import Context, Template
from django.test import TestCase

Expand Down Expand Up @@ -37,3 +39,26 @@ def test_can_change_app_id(self):
)
)
assert 'id="my_app"' in rendered

def test_data_page_valid_json(self):
rendered = Template("{% load inertia_tags %} {% inertia %}").render(
Context(
{
"page__": {
"component": "Index",
"url": "/",
"props": {"message": "Hello"},
"version": "1",
}
}
)
)

# Assert that a JSON-parsable string is found in the data-page attr
json_parsable_context_string = (
'{"component": "Index", "url": "/", "props": {"message": "Hello"}, "version": "1"}'
)
assert f"data-page='{json_parsable_context_string}'" in rendered

# Assert that the data-page attr value is a valid JSON string
assert type(json.loads(json_parsable_context_string)) == dict