Donentolon
Donentolon

Reputation: 1561

Working efficiently with Jinja Python templates in Pycharm

How can I leverage the syntax comprehension features of PyCharm when editing Jinja templates of Python code?

If I set the syntax of my template.py.jinja2 file to Python, I get numerous false positive syntax errors due to Jinja syntax, and and incorrect formatting as PyCharm assumes I'm typing invalid Python code.

Upvotes: 2

Views: 763

Answers (1)

TEH3OP
TEH3OP

Reputation: 41

Yup in a pycharm community edition templating is not available. As workaround you can run j2cli in "Before launch" section of your project "Run/Debug Configuration".

To do this first install j2cli into your project environment (Settings->Project ->Project Interpreter). Then create "Before launch" task: Run/Debug Configuration->Before launch click on "+" button then select "Run External tool". In "External tools" window click on "+" again and then fill "Create tool" window fields.

Here my configuration of "Create tool" window fields (for windows 10), which is processed any files with *.py.j2 extension and use corresponding *.py.json file as jinja config:

  • Name: as you wish
  • Description: as you wish
  • Program: forfiles
  • Arguments: /m *.py.j2 /c "cmd /c $PyInterpreterDirectory$\j2.exe @FILE @FNAME.json -o @FNAME"
  • Working directory: $ProjectFileDir$
  • Synchronize files after execution: {+check}

For linux "Create tool" window fields should look like this (!NOT TESTED!):

  • Program: find
  • Arguments: . -type f -name '*.py.j2' -exec sh -c '$PyInterpreterDirectory$\j2 $1.$2 $1.json -o $1'
  • Working directory: $ProjectFileDir$
  • Synchronize files after execution: {+check}

Upvotes: 1

Related Questions