pongo2 icon indicating copy to clipboard operation
pongo2 copied to clipboard

Added ability to customize the resolution of context contained variables.

Open blaubaer opened this issue 3 years ago • 5 comments

Added ability to customize the resolution of context contained variables, by:

  1. NamedFieldResolver.GetNamedField(name) and IndexedFieldResolver.GetIndexedField(index) interfaces
  2. Struct field pongo2:"..."

Plus: Added security enforcement to never use not exported fields.

Excerpt from the documentation

By the default sub variables are resolved by

  1. Field names inside structs
  2. Keys of values inside maps
  3. Indexes of values inside slices

This behavior can be customized using either struct tag "pongo2" like:

type MyStruct struct {
    FieldA string `pongo2:"uh"`
    FieldB string `pongo2:"yeah"`
}

my.tmpl:

{{ myStruct.uh }} {{ myStruct.yeah }}

...or by implementing NamedFieldResolver or IndexedFieldResolver.

type MyStruct struct {
    fieldA string
}

// GetNamedField implements NamedFieldResolver
func (s MyStruct) GetNamedField(s string) (interface{}, error) {
    switch s {
    case "uh":
        return s.fieldA, nil
    case "yeah":
        return "YEAH!", nil
    default:
        return nil, pongo2.ErrNoSuchField
     }
}

// GetNamedField implements IndexedFieldResolver
func (s MyStruct) GetIndexedField(s int) (interface{}, error) {
    switch s {
    case 0:
        return s.fieldA, nil
    case 1:
        return "YEAH!", nil
    default:
        return nil, pongo2.ErrNoSuchField
    }
}

my.tmpl:

{{ myStruct.uh }} {{ myStruct.yeah }}
{{ myStruct.0 }} {{ myStruct.1 }}

blaubaer avatar Feb 04 '22 11:02 blaubaer

Kudos, SonarCloud Quality Gate passed!    Quality Gate passed

Bug A 0 Bugs
Vulnerability A 0 Vulnerabilities
Security Hotspot A 0 Security Hotspots
Code Smell A 5 Code Smells

No Coverage information No Coverage information
0.0% 0.0% Duplication

sonarqubecloud[bot] avatar Feb 04 '22 11:02 sonarqubecloud[bot]

@flosch any updates on this? 🙂

blaubaer avatar Apr 21 '22 07:04 blaubaer

Thank you for your contribution. Please allow some more time for me to go through your PR.

flosch avatar Jun 23 '22 12:06 flosch