fix: Alpine.js JSON parsing error in x-data HTML attributes
Add tojson_attr Jinja2 filter that escapes double quotes to " for safe embedding in HTML attributes. The browser decodes entities before Alpine.js evaluates, so JSON parses correctly. Replaces |tojson with |tojson_attr in x-data attributes (select_recipe, recipe_list, base flash messages). Script tag usages are unaffected. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,9 +1,11 @@
|
||||
"""TieMeasureFlow Client - Flask Entry Point."""
|
||||
import json
|
||||
import os
|
||||
|
||||
from flask import Flask, redirect, url_for, session, request
|
||||
from flask_babel import Babel
|
||||
from flask_wtf.csrf import CSRFProtect
|
||||
from markupsafe import Markup
|
||||
|
||||
from config import Config
|
||||
|
||||
@@ -55,6 +57,24 @@ def create_app() -> Flask:
|
||||
session["language"] = lang
|
||||
return redirect(request.referrer or url_for("auth.login"))
|
||||
|
||||
@app.template_filter("tojson_attr")
|
||||
def tojson_attr_filter(value):
|
||||
"""JSON encode safe for HTML attributes (x-data, etc.).
|
||||
|
||||
Unlike |tojson, this escapes double quotes to " so the output
|
||||
can be safely embedded inside double-quoted HTML attributes.
|
||||
The browser decodes the entities before Alpine.js evaluates them.
|
||||
"""
|
||||
rv = json.dumps(value, ensure_ascii=False)
|
||||
rv = (
|
||||
rv.replace("&", "\\u0026")
|
||||
.replace("<", "\\u003c")
|
||||
.replace(">", "\\u003e")
|
||||
.replace("'", "\\u0027")
|
||||
.replace('"', """)
|
||||
)
|
||||
return Markup(rv)
|
||||
|
||||
@app.context_processor
|
||||
def inject_globals():
|
||||
"""Inject global variables into all templates."""
|
||||
|
||||
Reference in New Issue
Block a user