Jinja in NvChad.

While I’ve been “dusting off” some website building skills I’ve been a tad annoyed by the lack of support for Jinja templates in the text editor. It’s a minor thing - but to me it stuck out like a sore thumb. Luckily Neovim (NvChad distro), with which I’ve started experimenting recently, is super flexible… if you’re brave enough to dabble with its config ;) . After 2 evenings I had a pretty decent setup.

Syntax highlighting

  1. I’ve created ~/.config/nvim/lua/configs/filetypes.lua containing:
vim.filetype.add {
  extension = {
    ["jinja"] = "html",
  },
}
  1. I’ve added loading of this config in the ~/.config/nvim/init.lua
require "configs.filetypes"
  1. Ive added html and jinja support in Treesitter
TSInstall html
TSInstall jinja
  1. I’ve injected jinja syntax highlight into html component. This required editing this file:
~/.local/share/nvim/lazy/nvim-treesitter/queries/html/injections.scm

It needed:

((text) @injection.content
 (#set! injection.language "jinja"))

At this point it would be a good idea to delve a bit deeper into Treesitter. I have a suspicion there must be a better way to add those modified files (maybe somewhere in nvim config folder?) so this would be more portable.

Hints / snippets

When creating templates I enjoy having some productivity boosters at hand. For this - Emmet will suffice.

https://emmet.io/

  1. I’ve installed emmet-language-server through Mason.

I found it generally a good idea to check css, html, lua language servers at this time as well - as I’ve noticed in the logs Neovim has been looking for those.

  1. Prepared config for Emmet in ~/.config/nvim/lua/configs/lspconfig.lua.
local servers = {"html", "cssls", "basedpyright", "emmet_language_server",}
vim.lsp.config["emmet_language_server"] = {
	filetypes = {
		"html",
		"css",
		"scss",
		"jinja",
		"htmldjango",
		"jinja.html",
		"jinja",
	},
}

… of course making sure it’s before vim.lsp.enable(servers).

After this the highlights and snippets were working.

  1. As a bonus step jinja lsp could be added as well. Not sure whether I really need it, but I’m keeping it in mind for the future.

Lastly - I’ll need to look into adding some tweaks to the overall configs, so I’d get all those Treesitter components installed automatically in case they’re not there. Something like this should work:

return {
  {
    "nvim-treesitter/nvim-treesitter",
    event = { "BufReadPre", "BufNewFile" },
    build = ":TSUpdate",
    main = "nvim-treesitter.configs",
    opts = {
      ensure_installed = {
        "vim",
        "vimdoc",
        "lua",
        "html",
        "htmldjango",
        "css",
        "javascript",
        "json",
      },
      highlight = { enable = true, use_languagetree = true },
      indent = { enable = true },
      auto_install = true, 
    },
  },
}

P.S. Thx goes to Alexis12119 from NvChad Discord channel who gave me initial push with this.

Image(s):

Flora Hon, @Unsplash