#HAML: Checking variables in partials
Check if a page variable has been defined
Set variables in a page (page.html.haml) at the very biginning of the file:
---
variable: value
variable2: value 2
---
Logic either in a partial or in the page itself
- if data.page.variable2 != nil
/ Do whatever here
Check if a local variable has been passed at the partial call
Pass variables in a partial call from a page:
= partial(:"components/my_partial", :locals => { :variable => "value", :is_teaser => true, :limit => 4 })
Check the variables in the components/_my_partial.haml file
- if defined? variable2
/ Do whatever here
Check the variable in a ternary operator. Setting nil as false param in a ternary operator causes the property (class in the example) to be removed
%a.app_box{:href => "#", :class => (defined? extraclass) ? "#{extraclass}" : nil}
Check typeof a variable.
Possible types:
- variable = 5
- variable.is_a? Numeric // true
- variable.kind_of?(Numeric) // true
- variable.class // returns its Class, so its type
Check length of an array
Setting the array in page.html.haml or in /data/tabs.yml
---
tabs:
- title: tab1
href: #tab1
- title: tab2
href: #tab2
- title: tab3
href: #tab3
---
Checking the length of the array from a page
- data.page.tabs.length
Checking the length of the array from a data yaml file
- data.tabs.length
Check and assign default value to a variable.
If the variable was set and has already a value, this will be kept.
Otherwise the variable will be set and assigned the passed value.
In a page or partial, we call a partial with or without variables
= partial "components/article_overview/article_overview_unit"
= partial(:"components/article_overview/article_overview_unit", :locals => { :is_teaser => true, :limit => 4 })
Initialize local variables. They can be set in the partial load or not.
It is like: - limit = (defined? limit) ? limit : data.newsfeed.length. This way does not work.
- limit ||= data.newsfeed.length
- is_teaser ||= false