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

Added ability to customize the resolution of context contained variables. #287

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

blaubaer
Copy link
Contributor

@blaubaer blaubaer commented Feb 4, 2022

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 }}

1. `NamedFieldResolver.GetNamedField(name)` and `IndexedFieldResolver.GetIndexedField(index)` interfaces
2. Struct field `pongo2:"..."`
3. Added security enforcement to never use NOT exported fields.
@sonarcloud
Copy link

sonarcloud bot commented Feb 4, 2022

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

@blaubaer
Copy link
Contributor Author

@flosch any updates on this? 🙂

@flosch
Copy link
Owner

flosch commented Jun 23, 2022

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

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

Successfully merging this pull request may close these issues.

None yet

2 participants