Vim, Twig and html indentation

61 Views Asked by At

I'm trying to format html in Twig files, but I'm facing issues with the indentation. I've explored various solutions:

Prettier (via ALE plugin): Unfortunately, it doesn't support Twig.

Running php bin/console lint:twig templates/: This approach doesn't seem to work.

twig-lint: Unfortunately, it's outdated.

Adding let g:twig_indent_html = 1 and autocmd FileType twig setlocal ft=twig syntax=twig autoindent in .vimrc: This didn't yield the desired results.

Twig-CS-Fixer

prettier-plugin-twig-melody (and its fork : https://classic.yarnpkg.com/en/package/@supersoniks/prettier-plugin-twig-melody)

I've also tried https://github.com/nelsyeung/twig.vim, https://github.com/lumiliet/vim-twig and https://github.com/qbbr/vim-twig

Additionally, I experimented with using htmlhint via CocInstall coc-htmlhint, along with the configuration:

let g:coc_filetype_map = {
\ 'twig': 'html',
\ }

A short sample :

{% extends 'base.html.twig' %}
{% block title %}Welcome - Home{% endblock %}

{% block body %}
<h1>Welcome</h1>
<div>
<p>Hello!</p>
</div>
{% endblock %}

A short sample I want :

{% extends 'base.html.twig' %}
{% block title %}Welcome - Home{% endblock %}

{% block body %}
<h1>Welcome</h1>
<div>
    <p>Hello!</p>
</div>
{% endblock %}

However, I'm still encountering issues with Twig file indentation. Any further suggestions would be greatly appreciated. Thanks.

1

There are 1 best solutions below

0
kevgiraultdev On

With tidy, an external commande, it's possible : :<line-to-start>,<line-to-end>!tidy --show-errors 0 --show-body-only auto -qi -w 0

You can specify the lines as follows: :5,46!tidy --show-errors 0 --show-body-only auto -qi -w 0 for an application from line 5 to 46. Answer found here: Use HTML Tidy to just indent HTML code?

In .vimrc, you can add this for format on save :

augroup AutoTidy
  autocmd!
  autocmd BufWritePost *.html,*.twig execute 'silent! %!tidy --show-errors 0 --show-body-only auto -qi -w 0 --indent-spaces 4'
augroup END