ventojs / vento

🌬 A template engine for Deno & Node
https://vento.js.org/
MIT License
153 stars 9 forks source link

Improving spacing readability #34

Closed mattvr closed 4 months ago

mattvr commented 4 months ago

Vento templates currently require you to inline most if/for/print statements, omitting newlines, to avoid unnecessary spacing in the final output.

For example, if I have a template like this:

{{ for section of sections }}
{{ if section.title }}# {{ section.title }}{{ /if }}
{{ if section.subtitle }}## {{ section.subtitle }}{{ /if }}
{{ if section.content }}{{ section.content }}{{ /if }}
{{ /for }}

This would be nice and readable.. BUT, it will prints unnecessary newlines if any fields like subtitle aren't present. Thus, the template must be:

{{ for section of sections }}{{ if section.title }}# {{ section.title }}{{ /if }}{{ if section.subtitle }}## {{ section.subtitle }}{{ /if }}{{ if section.content }}{{ section.content }}{{ /if }}{{ /for }}

In order to have the correct output spacing. This spacing isn't purely aesthetic, as in the case of markdown and other formats it changes the result and correctness.

The workarounds are to either:

One solution could be to make a newline collapsing symbol (e.g. {| if myVar |} ... {| /if |}) which strips its output of adjacent newlines.

I don't have a great suggestion or preference for how to implement this, or even if it should be implemented, but I think vto templates could be much more readable with an improvement here.

wrapperup commented 4 months ago

Vento supports trimming whitespace before/after tags (see https://vento.js.org/syntax/print/#trimming-the-previous%2Fnext-content), so you can do something like this to trim the whitespace and get what you want:

{{ for section of it.sections }}
{{- if section.title }}
# {{ section.title }}
{{- /if -}}

{{- if section.subtitle }}
## {{ section.subtitle }}
{{- /if -}}

{{- if section.content }}
{{ section.content }}
{{- /if -}}
{{- /for }}

Other template engines like jinja2, eta also by default trim out the newlines. Might be a nice way to fix this issue without having to place trim markers everywhere.

oscarotero commented 4 months ago

Automatic trimming would be great, I've been playing with this idea in the first versions of Vento, but it's hard to do it well, because it doesn't generate good results in all cases.

If you have any idea how it would work, I'm open to try again.

mattvr commented 4 months ago

Oh, amazing, missed this. I can live with the trim markers, but I'd probably prefer auto-trimming by default (basically just negating the current marker behavior).

Thanks @wrapperup and @oscarotero!

wrapperup commented 4 months ago

Vento now has an auto trim plugin that you can enable (see https://vento.js.org/plugins/auto-trim/), give it a try and see if that works for you