简体   繁体   中英

Why is my template variable being ignored in ruby on rails?

I would like to have some code in my rails template layout to be invoked like this:

render :mytemplate, layout: 'mylayout', modal_title: 'My Title'

where mylayout exists as views/layouts/mylayout.html.haml . Inside, I want to use the following code to accept the modal_title but have a default value if the variable was not passed or was null:

- modal_title = 'Title' if not defined? modal_title or modal_title.nil?
-#Yes, somewhere I will print like: = modal_title

What do I expect : modal_title having "My Title" in the first case.
What do I have : modal_title having "Title" (the default value), and when I debug, I see modal_title existed before with value nil .

Why is my variable being ignored?

Specify local variables using the locals option:

render :mytemplate, layout: 'mylayout', locals: {modal_title: 'My Title'}

You can also simplify the default value logic in your template with try :

= try(:modal_title) || 'My Title'

If the modal_title variable exists and is not nil it will be used, otherwise it will print 'My Title'

In your case the modal_title being passed will always be nil in the template since it isn't being passed correctly. Use locals or object to pass desired variables to your template. Usually writing something like

render :partial => 'myTemplate' 

gets translated into

render :partial => 'MyTemplate', :locals => {:myTemplate => @myTemplate }

So either you can define an object that contains your default title 'My Title' or you can pass it with using locals explicitly

render partial => 'myTemplate', :locals => { :model_title => 'Your Title'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM