gbprod / tree-sitter-twig

Twig grammar for Tree-sitter
https://gb-prod.fr/tree-sitter-twig/
Do What The F*ck You Want To Public License
41 stars 3 forks source link

Twig component html syntax #17

Open fbuchlak opened 1 month ago

fbuchlak commented 1 month ago

Hi, are there any plans to support Component HTML Syntax? Specifically "injecting" output_directive in quoted html attributes for something like this <twig:foo :bar="variable|filter1|filter2" />.

gbprod commented 1 month ago

Interesting, I'll try to implement this soon

gbprod commented 1 month ago

I had a look on this and... it's really not easy. The main idea would be to split this parser in 3 different grammars (twig, twig_statement and twig_output) like we have in the php tree-sitter parser with php and php_only. With this split, it will be possible to inject twig_output grammar in html filetypes. This is a hard job for low gain... I think I will not do this soon :sweat_smile:

fbuchlak commented 1 month ago

Sure, nevermind. I've tried to create html injections for this, but without split grammar it seemed impossible.

My initial idea was to modify attribute value in injection by adding curly braces around that statement, but didn't find any solution. So <twig:foo :value="something" /> would "internally" become <twig:foo :value="{{ something }}" /> for treesitter and highlighting would be done with offset (but that's probably not possible)

fbuchlak commented 1 month ago

I've ended up with injecting javascript for those component attributes. It's not perfect and might be confusing, but it's better than nothing. At least for basic highlighting.

"solution"

; after/queries/html/injections.scm
;; extends

(element
  (_ (tag_name) @_tag
      (#lua-match? @_tag "^twig:%a")
  (attribute
    (attribute_name) @_attr
      (#lua-match? @_attr "^:%a")
    (quoted_attribute_value
      (attribute_value) @injection.content)
        (#set! injection.language "javascript")
    )))

and result looks like this 2024-10-22-15:39:45

gbprod commented 1 month ago

Interesting workaround!