Skip to main content

How to use jinja2 with IDEA

Did somebody already try to use the template module jinja2 with IDEA? I tried different code examples but don't get any output to html file/browser.

Brian Element Tue, 02/19/2019 - 11:10

I have never played with jinja2 but I have read-up on Django which looks like the same.  I haven't tried doing any integration with IDEA.  Are you trying to pull the information from IDEA and then place it in a browser using jinja2?

klmi Mon, 04/15/2019 - 10:58

> Are you trying to pull the information from IDEA and then place it in a browser using jinja2?
Yes that was the idea. I am missing an easy output function from IDEA (10.3). Up to now I am using tkinter messageboxes for smaller messages like in the follwing example:
 
import tkinter
from tkinter import Tk, messagebox
root = Tk()
 
# workaround: hide the Tk root window
root.withdraw()
 
# display error
messagebox.showerror("Error", "ERROR: ...")
root.quit()
 
# display messagebox 
messagebox.showinfo("Messagebox", "Hello World! \n\n Click OK to close window.")
root.destroy()     # root.quit() will also work
 
 
But that's no serious option for longer outputs (f.e. pandas DataFrames).
In such cases I'm redirecting stdout to a textfile:
 
import sys
org_stdout = sys.stdout
f = open("C:\output.txt", "w")
sys.stdout = f
print("hello world")
sys.stdout = org_stdout
f.close()
 
I also tried to redirect the whole console output to a tk text widget but that is not as easy as file output.

klmi Mon, 07/01/2019 - 09:29

In the meantime I found out how to use jinja2 with IDEA and want to share knowledge. jinja2 allows to output text which is based on a template. It depends on markupsave which is also part of the IDEA Python modules.
 
First simple example:
 
from jinja2 import Template
name = "KAAN"
tmpl = Template("Hello {{name}}!<BR>")
msg = tmpl.render(name=name)
 
# no console when using Python with IDEA
#print(msg)
 
# save output to file
ofile=open("jinja_output.html", "w")
ofile.write(msg)
ofile.close()
 
 
Second example with template file:
 
# load template file
with open("jinja_template.html") as tfile:
tmpl = Template(tfile.read())
tfile.close()
 
# save output
ofile=open("jinja_output.html", "w")
ofile.write(tmpl.render(variable = "Test", item_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
ofile.close()
 
 
You will need the following template file "jinja_template.html"
 
<!DOCTYPE html>
<html>
<head>
<title>{{ variable|escape }}</title>
</head>
<body>
{%- for item in item_list %}
{{ item }}{% if not loop.last %},{% endif %}
{%- endfor %}
</body>
</html>