Skip to content

Instantly share code, notes, and snippets.

@orioltf
Last active July 6, 2019 23:45
Show Gist options
  • Save orioltf/3145400 to your computer and use it in GitHub Desktop.
Save orioltf/3145400 to your computer and use it in GitHub Desktop.
#HAML: Checking variables in partials
  1. Check if a page variable has been defined

    1. Set variables in a page (page.html.haml) at the very biginning of the file:

      ---
      variable: value
      variable2: value 2
      ---
    2. Logic either in a partial or in the page itself

      - if data.page.variable2 != nil
      	/ Do whatever here
  2. Check if a local variable has been passed at the partial call

    1. Pass variables in a partial call from a page:

      = partial(:"components/my_partial", :locals => { :variable => "value", :is_teaser => true, :limit => 4 })
    2. Check the variables in the components/_my_partial.haml file

      - if defined? variable2
      	/ Do whatever here
    3. 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}
  3. Check typeof a variable.
    Possible types:

    • Integer
    • Numeric
    • Fixnum
    • Array
    - variable = 5
    - variable.is_a? Numeric		// true
    - variable.kind_of?(Numeric)	// true
    - variable.class				// returns its Class, so its type
    
  4. Check length of an array

    1. 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
      ---
    2. Checking the length of the array from a page

      - data.page.tabs.length
    3. Checking the length of the array from a data yaml file

      - data.tabs.length
  5. 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.

    1. 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 })
    2. 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
@sbpipb
Copy link

sbpipb commented Jul 19, 2018

@saadbinakhlaq this actually works. thanks mate
If the if/else is used for text, this would be the best solution.

  • limit ||= data.newsfeed.length
  • is_teaser ||= false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment