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
Modify object #313
Comments
Duplicate of #307. I don't think nunjucks will support this. |
Thanks for refing. I've missed that issue. Jinja has Considering it, maybe this issue should be closed and 307 reopened with new information? |
I don't think this is really a duplicate of #307, since that was specifically about |
Hi carljm. Thanks for reply. So, in such case this issue should be reopened as enhancement? |
@ArmorDarks Well, only if an implementation of |
Sorry for resurrecting quite old issue. I just hope that following information might be useful for beginners, who stuck with same problem. Solution is quite simple — to write few custom filters, they will work like a charm for modifying of arrays or objects. Few very basic examples for arrays modifications (CoffeeScript): # Replace last value of array with `value`
# @example {% set modifiedArray = myArray|popIn('myValue') %}
env.addFilter 'popIn', (array, value) ->
array.pop()
array.push(value)
array
# Add `value` to the end of array
# @example {% set modifiedArray = myArray|pushIn('myValue') %}
env.addFilter 'pushIn', (array, value) ->
array.push(value)
array With same approach you can write filters for setting objects properties too. Unfortunately, there is no other way around until someone will implement |
This looks simpler and sufficient for this case: env.addFilter('setAttribute', function(dictionary, key, value) {
dictionary[key] = value;
return dictionary;
}); Usage {% set myDict = {"key1": 0, "key2": 0, "key3": 0}%}
{% set myDict = myDict|setAttribute('key2', 123) %}
{{myDict['key2']}} ... prints "123" as expected. |
@jan-dolejsi the output is correct. You've set |
Thank you! I had the same problem, this filter solves it! |
Works like a charm! |
Hello
Let's imagine we're having an object:
Is there any way to modify it's properties without overriding whole object?
For example, like:
or to add another key:
Currently such attempts will return error
TypeError: Cannot call method 'charAt' of undefined
, of course.Now I wonder, is there any workaroud for it, or it isn't possible and won't be ever possible too?
If I do understand it right, jinja has such possibility, with
do
blockhttp://stackoverflow.com/questions/11047886/modifying-dictionary-attributes-in-jinja2
The text was updated successfully, but these errors were encountered: