Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reference next value in stencil template loop #1162

Open
danielsinclairtill opened this issue Apr 11, 2023 · 0 comments
Open

Reference next value in stencil template loop #1162

danielsinclairtill opened this issue Apr 11, 2023 · 0 comments

Comments

@danielsinclairtill
Copy link

danielsinclairtill commented Apr 11, 2023

Question

Is there a way to reference the current and the next variable in a stencil template for loop?

example:

{% for variable in type.allVariables %} 
current var: {{variable.name}}
next var: {{forloop.nextValue.name}} // reference next value in loop
{% endfor %}

Context

I am trying to make a template to auto generate a Step Builder pattern like the example below.
I would require to have a reference to the next variable name in the for loop to correctly define the next protocol return type.

Source Input:

struct Person {
    var name: String = ""
    var age: Int = 0
}

Template:

{% for variable in type.allVariables %}
protocol {{type.name}}{{variable.name|upperFirstLetter}}Step {
    func set{{variable.name|upperFirstLetter}}(_ {{variable.name}}: {{variable.typeName}}) -> {{type.name}}{{forloop.nextValue.name|upperFirstLetter}}Step
}
{% endfor %}

Expected Builder Output:

protocol PersonNameStep {
    func setName(_ name: String) -> PersonAgeStep
}

protocol PersonAgeStep {
    func setAge(_ age: Int) -> PersonBuildStep
}

Rest of code:

protocol PersonBuildStep {
    func build() -> Person
}

class PersonBuilder: PersonNameStep, PersonAgeStep, PersonBuildStep {
    var person = Person()

    func setName(_ name: String) -> PersonAgeStep {
        person.name = name
    }
    ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant