handlebars-rust icon indicating copy to clipboard operation
handlebars-rust copied to clipboard

Render a template with keeping indentation level of multi-line strings

Open inf17101 opened this issue 11 months ago • 2 comments

I have the following issue with the default rendering:

name: some name
data:
  key1: |
    {{value1}}

If I substitute it with a multi-line string using the default rendering syntax like above, then indentation level is lost and the resulting yaml is invalid:

substitution_string: Line1\nLine2\nLine3

name: some name
data:
  key1: |
    Line1
Line2
Line3

What I need per default is:

name: some name
data:
  key1: |
    Line1
    Line2
    Line3

I have tried out to register a partial because then the indentation level is kept and the rendering is fine. But then I need a custom syntax for my users like {{> indent value1}} (assume here the partial is registered with name 'indent').

Is there a programmatic way in the handlebars-rs library to enable to keep indentation level before rendering and disable it afterwars? I need it for one field and I need to change the default behavior.

What I have tried out: Register a template with is_partial = true, but the member and the Template::compile2 to define TemplateOptions is also private.

Is there any way to keep indentation level with the default syntax without defining special helpers or custom syntax?

inf17101 avatar Jan 24 '25 08:01 inf17101

Hello @inf17101 , Let me know if this will work for you

name: some name
data:
  key1: |
    {{#each values}}
    {{this}}
    {{/each}}

where values is ["line1", "line2", "line3"]

A playground link:

https://sunng87.github.io/handlebars-rust/?tpl=name%3A%20some%20name%0Adata%3A%0A%20%20key1%3A%20%7C%0A%20%20%20%20%7B%7B%23each%20values%7D%7D%0A%20%20%20%20%7B%7Bthis%7D%7D%0A%20%20%20%20%7B%7B%2Feach%7D%7D&data=%7B%22values%22%3A%5B%22line1%22%2C%20%22line2%22%2C%20%22line3%22%5D%7D

sunng87 avatar Jan 25 '25 14:01 sunng87

Thank you for your answer, but that is not my actual question. I search for a programmatic way not using a different syntax to achieve the correct result. But I will keep the partial with a custom name to let our users render templates with multi-line strings while keeping indentation level.

inf17101 avatar Feb 03 '25 09:02 inf17101