optional local variables in rails partial templates: how do I get out of the (defined? foo) mess?

前端 未结 12 1978
没有蜡笔的小新
没有蜡笔的小新 2020-12-04 04:41

I\'ve been a bad kid and used the following syntax in my partial templates to set default values for local variables if a value wasn\'t explicitly defined in the :locals has

相关标签:
12条回答
  • 2020-12-04 05:34

    This is a derivative of Pablo's answer. This allows me to set a default ('full'), and in the end, 'mode' is set in both local_assigns and an actual local variable.

    haml/slim:

    - mode ||= local_assigns[:mode] = local_assigns.fetch(:mode, 'full')
    

    erb:

    <% mode ||= local_assigns[:mode] = local_assigns.fetch(:mode, 'full') %>
    
    0 讨论(0)
  • 2020-12-04 05:35

    How about

    <% foo ||= default_value %>
    

    This says "use foo if it is not nil or true. Otherwise assign default_value to foo"

    0 讨论(0)
  • 2020-12-04 05:36

    In my case, I use:

    <% variable ||= "" %>
    

    in my partial.
    I don't have idea if that is good but for my is OK

    0 讨论(0)
  • 2020-12-04 05:37

    I do this:

    <% some_local = default_value if local_assigns[:some_local].nil? %>
    
    0 讨论(0)
  • 2020-12-04 05:37

    I think a better option that allows for multiple default variables:

    <% options = local_assigns.reverse_merge(:include_css => true, :include_js => true) %>
    <%= include_stylesheets :national_header_css if options[:include_css] %>
    <%= include_javascripts :national_header_js if options[:include_js] %>
    
    0 讨论(0)
  • 2020-12-04 05:41

    If you do not want to pass local variable to partial each time you call it you do this:

    <% local_param = defined?(local_param) ? local_param : nil %>
    

    This way you avoid undefined variable error. This will allow you to call your partial with/without local variables.

    0 讨论(0)
提交回复
热议问题