valyala / quicktemplate

Fast, powerful, yet easy to use template engine for Go. Optimized for speed, zero memory allocations in hot paths. Up to 20x faster than html/template

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Feature Request] ignoring new line and tab indents in special tags

muthukrishnan24 opened this issue · comments

I am using QTPL for go code generation.
i see that it is intended for html template. But it can be very useful for all kind of text generation.

issue #27 does not cover my case

below is a sample template func to explain my use case

{% func GenTestFunc() %}
	func TestFunc(a int, b int) int {
		var sum int
		{% for i := 0; i < 10; i++ %}
			sum += {%d i %}
		{% endfor %}
		return sum
	}
{% endfunc %}

I'm getting:

	func TestFunc(a int, b int) int {
		var sum int
		
			sum += 0
		
			sum += 1
		
			sum += 2
		
			sum += 3
		
			sum += 4
		
			sum += 5
		
			sum += 6
		
			sum += 7
		
			sum += 8
		
			sum += 9

		return sum
		
	}

expect something like this:

func TestFunc(a int, b int) int {
	var sum int
	sum += 0
	sum += 1
	sum += 2
	sum += 3
	sum += 4
	sum += 5
	sum += 6
	sum += 7
	sum += 8
	sum += 9
	return sum
}

i tried {% stripspace %} and {% collapsespace %} but they are not sufficient

  1. {% func %}, {% for %}, {% if %} and other tags, take string between as it is, to improve readability, these blocks can ignore first tab/space indent, or special tag to ignore them
  2. also each the block, create a new line before them

i had to write this to get the intended output

{% func GenTestFunc() %}
func TestFunc(a int, b int) int {
	var sum int{% for i := 0; i < 10; i++ %}
	sum += {%d i %}{% endfor %}
	return sum
}
{% endfunc %}

My Proposal for this issue
Pull request is this.

Tag opening mark "{%-" strip tail blanks form previous text.
Tag ending mark "-%}" strip blanks to new line from next text.
Below code

{% func GenTestFunc() %}
func TestFunc(a int, b int) int {
	var sum int
	{%- for i := 0; i < 10; i++ -%}
	sum += {%d i %}
	{%- endfor %}
	return sum
}
{% endfunc %}

outputs

func TestFunc(a int, b int) int {
	var sum int
	sum += 0
	sum += 1
	sum += 2
	sum += 3
	sum += 4
	sum += 5
	sum += 6
	sum += 7
	sum += 8
	sum += 9

	return sum
}

Merged the PR

The feature is available starting from v1.4.0.