I have the following form in an AMP website to display an input for an email registration dialog:
<form method="post" action-xhr="/amp-register-email" target="_top" id="emailForm" enctype="application/json">
<label for="email">Email Address:</label>
<input type="email" id="email" name="email" required on="change:AMP.setState({emailState: {hasError: false}})">
<div [hidden]="!emailState.hasError" hidden>
Email incorrect.
</div>
<input type="submit" value="Registrieren">
<div submitting>
<template type="amp-mustache">
<div class="spinner">X</div>Wait...
</template>
</div>
<div submit-success>
<template type="amp-mustache">
Registration successful.
</template>
</div>
<div submit-error>
<template type="amp-mustache">
Error: {{ errorMessage }}
</template>
</div>
</form>
Now in the backend I got the following method in my flask backend:
@app.route('/amp-register-email', methods=['POST'])
def register_email():
email = request.form.get("email", None)
# Just for testing purpose I am always sending an error message
response_dict = {"errorMessage": "Die eingegebene E-Mail-Adresse ist bereits registriert."}
response = Response(response=json.dumps(response_dict), mimetype="application/json", status=406) # 406 not acceptable
return response
However, this errorMessage
is not displayed in the part of the form. Instead I only see "Error:" and nothing afterwards.
How can I send a customized error message from the backend to the frontend and display it in an AMP website?
It appears that Jinja was interpreting your Mustache template variable ({{ errorMessage }}
) as a Jinja variable - as both were using the same {{ }}
delimiters.
As per your comment, you managed to fix this by using the Jinja {% raw %} tag
.
The other way which you could fix this would be to redefine the delimiters that Mustache uses (perhaps instead of using {{ }}
for your mustache templating delimiters you could use [[ ]]
instead).