How to use jinja2 with IDEA

5 posts / 0 new
Last post
klmi
Offline
Joined: 02/13/2019 - 08:41
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's picture
Brian Element
Offline
Joined: 07/11/2012 - 19:57

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
Offline
Joined: 02/13/2019 - 08:41

> 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
Offline
Joined: 02/13/2019 - 08:41

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>

Brian Element's picture
Brian Element
Offline
Joined: 07/11/2012 - 19:57

Hi klmi,

Thanks for sharing.  Did you see my word find script (little demo script) that mixes IDEAScript with python.

http://ideascripting.com/IDEA_Lab/word-find

Brian