'Can we render .ejs file using flask?
I am currently learning flask framework after completing my node.js and express. I just want to know can we render .ejs file also in flask as we can do in node js.
Solution 1:[1]
As far as I can tell there is no Python library capable of rendering .ejs (Embeddable JavaScript Template) files. This is most likely because of the fact that ejs files permit a lot of JavaScript syntax (if not arbitrary JavaScript). So implementing that within Python would be a pain. However there are a ton of templating languages with Python support (see this page on the Python wiki for a list). That said, you could theoretically just execute ejs as a separate process:
import json
import subprocess
from flask import Flask
app = Flask("app")
data = {
"title": "Example",
"user": { "firstName": "World" },
"messages": [ "foo", "bar", "baz" ]
}
@app.route("/")
def hello_world():
# Note: this assumes you have globally installed ejs with: npm install -g ejs
ejsRenderer = subprocess.Popen(
["ejs", "example.ejs"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
rendered = ejsRenderer.communicate(bytes(json.dumps(data), "utf8"))[0]
ejsRenderer.stdin.close()
ejsRenderer.wait()
return rendered
app.run(host="0.0.0.0", port=8080)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Paul Wheeler |
