liquid
liquid copied to clipboard
"strict_variables" option does not take into account defaults
I would like to use strict_variables: true, but it returns an error for an unassigned variable even if that variable has a default. Is there any way to throw an error if a variable is unassigned and doesn't contain a default?
By default, do you mean you are using a Hash default_proc?
We are relying on the key? method to tell us if the variable is assigned, since the [] method could return nil if the key is assigned the nil value or if the key is missing. If the default_proc returned nil, then it would also be ambiguous if we don't rely on key?.
If we wanted to support this, we could do the key? check only if a nil value is returned from the [] method, so a default value of nil returned from Hash#[] would result in an undefined variable error. Would that match the behaviour that you expected?
By default, do you mean you are using a Hash
default_proc?We are relying on the
key?method to tell us if the variable is assigned, since the[]method could returnnilif the key is assigned thenilvalue or if the key is missing. If the default_proc returnednil, then it would also be ambiguous if we don't rely onkey?.If we wanted to support this, we could do the
key?check only if anilvalue is returned from the[]method, so a default value ofnilreturned fromHash#[]would result in an undefined variable error. Would that match the behaviour that you expected?
By default I mean the default filter. A nil variable that has a value with the default filter with won't be nil so I don't want strict_variables to throw an error for it.
Hello any update on this? I am looking for anyway to either require a value or a default for the variable
You mean you have something {{ my_var | default: "Some Value" }} where my_var hasn't been assigned? If that is the case, then the error happens before getting to the filter, which sounds very similar to issue https://github.com/Shopify/liquid/issues/1034
Correct that is exactly the case. The LiquidJS library has an option called lenient_if that covers this case to get the desired behavior
I'm trying to use lenient_if but it doesn't work for this use case, where I want to set a default value if it isn't passed into my template:
{%- assign my_var = my_var | default: "some value" -%}
I still get:
Liquid error: undefined variable my_var
@emawby I would please like to expand the scope of this issue from:
"strict_variables" option does not take into account defaults
to:
Implement lenient_if for use with "strict_variables"
or the more generic:
Add some legal way to check the existance of variable with "strict_variables"