Is there a way to use Object.prototype.hasOwnProperty() in an expression?

34 views
Skip to first unread message

Tory Berra

unread,
Feb 19, 2016, 10:56:41 PM2/19/16
to Nunjucks
When a form is posted to my handler, and it fails validation I spit back the view with a local variable called errors.body. It will have various properties on it with names that correspond with the form input names.

A tricky situation is on checkboxes that dont have values. Nunjucks will take "" as falsy, which makes sense.

value="{{ value }}" {{ "checked" if errors.body[name] }} />

Is there a way to use Object.prototype.hasOwnProperty() in my expression?

Carl Meyer

unread,
Feb 19, 2016, 11:10:19 PM2/19/16
to nunj...@googlegroups.com
Hi Tory,

On 02/19/2016 08:56 PM, Tory Berra wrote:
> When a form is posted to my handler, and it fails validation I spit back
> the view with a local variable called errors.body. It will have various
> properties on it with names that correspond with the form input names.
>
> A tricky situation is on checkboxes that dont have values. Nunjucks will
> take "" as falsy, which makes sense.
>
> |
> value="{{ value }}"{{"checked"iferrors.body[name]}}/>
> |

I don't fully understand the use case here. Is it with `value` or with
`errors.body[name]` that you're concerned about an empty string
evaluating to false? Seems like the latter, but why would "checkboxes
don't have values" imply that the error would be an empty string? In any
case, I can answer the general question:

> Is there a way to use Object.prototype.hasOwnProperty() in my expression?

Not directly, but fairly easily -- you just need to define a filter
function that uses `hasOwnProperty` and add it to your environment using
`addFilter`, then you could do something like `if
obj|hasOwnProperty(name)` in your template (if you named your filter
`hasOwnProperty`).

Carl

signature.asc

Tory Berra

unread,
Feb 19, 2016, 11:39:27 PM2/19/16
to Nunjucks
Perfect thanks Carl.

To clarify a bit, a checkbox that is checked, and that does not have  a value will show up on req.body as  { some_checkbox : "" }

If I try and restore the form values when a post fails, I need to set the "checked" attribute on the checkbox.

You can see how {{ "checked" if body["name"] }} would not work in this situation, because even though that key exists on body, it has no value. the name variable comes from the macro parameter, which is manually provided by the developer when building the form.

Hope this helps, didnt mean to confuse with my code snippet.
Reply all
Reply to author
Forward
0 new messages