Background
After completing a form I redirect the user to the Post page, with the content he has input on that form. The description input, which is a textarea, has support for markdown text; that markdown text I want to parse before the page loads into html using showdown. After submitting the form I save the text in a Project object that I pass on the route to the html.
Route called when form is submitted
''' Route of dynamically generated post. '''
@bp.route('/projects/post/<post_id>')
def post(post_id):
.....
return render_template('post.html', title=f'Project {post_id}', project=project)
I want to be able to send the `project.background_input' from HTML to javascript to I can use
const bg_intro = document.getElementById('project-description-intro')
bg_intro.innerHTML = ` ${converter.makeHtml(project.background_intro)} `
I tried the following:
In my script before the
bundle.jswith the module that converts markdown into html<script type=text/javascript> dosth({{ project.background_intro|tojson|safe }}); // ERROR OBJECT OF TYPE UNDEFINED </script> <script src="{{ url_for('static', filename='assets/js/post-convert/bundle.js') }}"></script>Create global js variable.
Uncaught ReferenceError: background_intro is not defined
<script type=text/javascript>var text = {{project.description_intro}};</script> // Uncaught ReferenceError: description_intro is not defined <script src="{{ url_for('static', filename='assets/js/post-convert/bundle.js') }}"></script>
How should I pass my jinja2 variable to javascript?
EDIT:
I captured the output of my project.description_intro on my post route as following:
print(f'Type is {type(project.description_intro)} and the content: {project.description_intro}')
With the corresponding output:
Type is <class 'str'> and the content: This is a simple text, for testing purposes. This is **bold**. This is a list:
- l1
- l2
EDIT2:
bundle.js
function dosth(text1){
console.log(text1); // 22:196 Uncaught ReferenceError: dosth is not defined
}
html file
<script type=text/javascript>
dosth({{ project.description_intro|tojson|safe }});
</script>