Err the Blog Atom Feed Icon
Err the Blog
Rubyisms and Railities
  • “Content for Whom?”
    – Chris on January 08, 2007

    Advertisement

    Larry is building a personal home page. He’s using Ruby on Rails and fla-fla-flying. Why, at the rate he’s going, link groups and banner exchanges will be begging him to join in no time flat.

    Meet Larry.

    Just recently he was Googling and came across a post on Err the Blog titled Content for Whom? While the writer of said blog is a bit of a flake, Larry was able to make his site more dynamic and DRY using content_for after reading the post. Here’s how.

    The Sidebar

    We all know Rails compiles views before it compiles the layout. That is, if you set @page_title in your view, you may reference it in your layout. Something like <title>My Site :: <%= @page_title %></title>. content_for is no different: it allows you to ‘assign’ a chunk of HTML or Ruby to a symbol which may be referenced in your layout.

    Here’s Larry’s layout:
    <html>
    <head><title>Larry's Personal Home Page</title></head>
    <body>
      <table width="100%">
        <tr><td>
          <%= yield %>
        </td><td>
          <%= yield :sidebar %>
        </td></tr>
        <tr><td colspan="2" align="center">
          Copyright (c) 2006 Larry
        </td></tr>
      </table>
    </body>
    </html>
    

    The first yield, clearly, will be replaced with Larry’s view when rendered. The second yield is a bit different: he’s passing it a symbol, saying he wants to yield :sidebar at that point in time—whatever :sidebar may be.

    Let’s look at Larry’s view:
    <font color="red">Welcome to my website.</font><br>
    <img src="under_construction.gif"><br>
    <font color="blue">It was coded by hand in notepad.</font><br>
    <font color="green">Tell me what you <blink>think!!</blink></font><br>
    
    <% content_for :sidebar do %>
      Hot Links<br>
      <a href="http://www.netscape.com">Netscape</a><br>
      <a href="http://www.lycos.com">Lycos</a><br>
      <a href="http://www.walmart.com">Wal Mart</a><br>
    <% end %>
    

    You got it, right? yield :sidebar is going to be replaced by whatever block is passed to content_for :sidebar. In this case, Larry’s sidebar.

    Ah, solidarity:

    That’s fairly useful, but it means Larry has to set :sidebar in every view if he wants one to always show up. A nice thing to do is provide a default.

    The Conditional

    Larry just needs to replace, in his layout,
    <%= yield :sidebar %>
    

    with

    <%= (sidebar = yield :sidebar) ? sidebar : render(:partial => 'shared/sidebar') %>
    

    Now shared/sidebar will always be rendered unless a view defines :sidebar with content_for. In those cirumstances the view’s :sidebar will be shown. So, you can override a default element of the layout. Nice.

    As an aside, you can access @content_for_sidebar directly but that’s not legit. Deprecated.

    The Faux Nested Layout

    Imagine Larry has a whole bunch of controllers. He is happy with the default sidebar trick but there’s still an issue: he wants all the HomeController views to have a standard sidebar and all the UsersController to have a different standard sidebar.

    One idea is to remove the shared/ from the conditional in his layout:

    <%= (sidebar = yield :sidebar) ? sidebar : render(:partial => 'sidebar') %>
    

    Now either home/_sidebar.rhtml or users/_sidebar.rhtml will be rendered depending on which controller you’re in. The problem is Larry loses his ‘catch-all’ default sidebar and is forced to create a _sidebar.rhtml file for every controller. Not cool.

    I tell Larry, “Throw away that code and change it back to the conditional which uses shared/sidebar. Now, think about layouts. If you have a HomeController and home.rhtml exists in your views/layouts/ directory, Rails will render that. Perfect place to define a home-wide sidebar, yeah?”

    views/layouts/home.rhtml:
    <% content_for :sidebar do %>
      Cool Pages on My Site:<br>
      <a href="/home/lonely">LonelyGrrl Videos</a><br>
      <a href="/home/pagerank">My Google Pagerank</a><br>
      <a href="/home/web2">Web 2.0 Logo Generator (lol)</a>
    <% end %>
    <%= render :file => 'layouts/application' %>
    

    This ‘layout’ file is setting :sidebar then rendering the application layout. Larry just needs to do the same thing for views/layouts/users.rhtml and he’s all set.

    Let’s recap. Larry can now define content_for :sidebar in a view, define it for a whole set of controller views, and also have a site-wide default. All at the same time. Talk about power!

    One caveat here is that content_for appends content. It don’t replace it. If you’re defining :sidebar in a view under views/home/, using the above example, you’re going to end up with what looks like two sidebars: the one in the home.rhtml layout file and the one in your specific view.

    And hey, if you want real nested layouts there’s a plugin for Ruby on Rails available. So get that.

    The Stylesheet

    Years pass. Larry learns a bit of CSS and begins working for a big, corporate website. Special promotions are demanded by advertisers: they want to advertise on pages which have their own unique style with which “the kids” can identify. Something street. Like those PSP graffiti ads.

    Larry, now a seasoned Rails pro, knows this is not a problem. content_for, after all. He comes up with this:

    <html>
    <head>
      <title>Big Corporate Website 4.0 Beta</title>
      <%= stylesheet_link_tag 'main' %>
      <%= yield :stylesheet %>
    </head>
    <body>
      <%= yield %>
    </body>
    </html>
    

    See it? If there’s no content_for :stylesheet, everything works. The yield :sidebar just returns nil. However, Larry can also bust out a content_for :stylesheet in any view to add a bit more spice to that particular page. Like:

    <% content_for :stylesheet do %>
      <%= stylesheet_link_tag 'railsconf' -%>
    <% end %>
    
    <h1>Welcome to our RailsConf information page!</h1>
    

    Now his h1’s can be as nutty as all hell and won’t affect the other h1’s in his meticulously crafted website. He can even change the background color. Something pastel, I’d imagine.

    The Fin

    All of this content_for magic lovingly wraps ActionView’s capture method. The Rails API has the scoop. Just try to remember :layout is off limits when dealing with content_for. If you use it, you’ll just be messing with what gets displayed in your layout’s vanilla <%= yield %> call. Also heed this warning from the API docs: “Beware that content_for is ignored in caches. So you shouldn’t use it for elements that are going to be fragment cached.”

    The web’s really all about HTML, amirite? I dig the stuff Bruce is doing and hey, SimplyHelpful looks like a step in the right direction. My memories of Smarty are cherised, but ActionView has stolen my heart.

  • Kevin Marsh, 3 months later:

    Glad to hear Larry learned CSS, those tables for layout in the first example were making me nervous!

    (Great tips, too!)

  • atmos, 3 months later:

    Nicely done.

  • Peter Bex, 3 months later:
    Interesting! I’d like to note one thing, though. Your code
    <%= (sidebar = yield :sidebar) ? sidebar : render(:partial => 'shared/sidebar') %>
    is a little bulky. You could just write
    <%= yield :sidebar || render(:partial => 'shared/sidebar') %>
    . Unless you’re using the sidebar content later on in the layout, you don’t need the conditional & assignment.
  • Peter Bex, 3 months later:

    Hmm, looks like the Textile got a little screwed :(

  • sotakone, 3 months later:

    Good post! Larry is my hero for today.

  • Andrey, 3 months later:

    small comment to Peter’s post. The line should look like: <%= (yield :sidebar) || render(:partial => ‘shared/sidebar’) %>

  • Jens, 5 days later:

    What if the sidebar content is dynamic though, and needs to read from several different tables (models) regardless of which view is currently being shown. How should this data be prepared for the sidebar?

  • znupy, about 1 month later:

    Jens in this case you put before_filter to controller that needs sidebar data for all (not necessary) actions (views).

  • supaspoida, 3 months later:

    Can you clarify this bit for me?

    “Just try to remember :layout is off limits when dealing with content_for. If you use it, you’ll just be messing with what gets displayed in your layout’s vanilla <%= yield %>”

    How would you go about overriding the layout for a particular method or class then? Say I have an default application layout defined, but also have 3 more layouts which might be used throughout the site, and I am using yield to load up sub layouts which contain the content_for blocks?

  • eastwoodsz, 10 months later:

    Nice post,I was keep looking for a solution to avoid having to add “content_for” in each view for the sidebar before came to your site.

    I’wonder if there is any way to keep the sidebar unchanged for each session,that is to say,init only once,of course dynamic content,must I use ajax to render each view to a partical to archive this kind of behavior?

    Thanks!

  • Chris, 12 months later:

    Calling yield on a nil value returns an empty string in rails 2.0, so you need to change the logic in your layouts that call yield to something like this:

    <%= :sidebar ? (yield :sidebar) : render(:partial => ‘shared/sidebar’) %>

  • Antony, about 1 year later:

    Thanks for this. Didn’t have a clue ‘til I read this page

  • aaaq, about 1 year later:

    The best article, thanks to the author. good jokes, funny jokes

  • Ernie, about 1 year later:

    Chris,

    I know I'm late to this party, but you can't really check for existence of a Symbol like that, since the instant Ruby sees :sidebar the symbol exists. Fire up irb and try any number of conditionals:

    :garbage_symbol_to_test ? ‘yes’ : ‘no’ => “yes”

  • Ernie, about 1 year later:

    Curses! Foiled again by my insistence on indentation in corresponence vs Textile.

    Trying again:

    I know I’m late to this party, but you can’t really check for existence of a Symbol like that, since the instant Ruby sees :sidebar the symbol exists. Fire up irb and try any number of conditionals:

    :garbage_symbol_to_test ? ‘yes’ : ‘no’
    => “yes”
  • Heart Tattoos, about 1 year later:

    Tattoos Celtic Tattoos Lower Back Tattoos Dragon Tattoos Skull Tattoos Heart Tattoos Butterfly Tattoos Chinese Tattoos Layered Hair Styles Layered Hairstyles Emo Hairstyles Medium Hairstyles Bang Hairstyle Prom Hairstyle Hair Coloring Heart Lower Back Tattoos

  • reach, about 1 year later:

    I suggest 2 FLV Converter for Mac software. One is powerful in download YouTube Videos and convert downloaded FLV files; the other is professional in video converting, which can not only convert .flv video to all media formats, but also can convert all kinds of video formats to .flv, plus popular videos.

  • senior day care centers, about 1 year later:

    For anyone with old or elderly loved ones, it is important to take care of your central florida retirement communities brookdale senior living inc kelly home care services boston senior home care senior home care inc new jersey living will form new jersey living will senior day care centers florida golf retirement communities senior apartments in las vegas senior apartments las vegas in hopes making sure you or your old / elderly loved ones are taken care of with the best nursing care available.

  • lezbiyen videoları, about 1 year later:

    sikiş porno sex video izle iyi porno uzun porno yeni pornolar porno seyret sex seyret porno filmler sex izleyin sex izle porno sex erotik porn video türk porno canlı porno porno izle porno porno film sex filmleri porn video porno film sex seyret porno video seyret orgazm porno seks izle erotik video sex videolar yetişkin video sex video izle porno video izle bedava porno 18 video seks porno sıcak izle yetişkin film sikiş seyret sex amatör videolar teen video erotik videolar yetişkin video yetişkin videolar pornolar porno video teen kızlık bozma sikiş sikiş video seks türban sex sex erotik seks izle sıcak ateşli

  • asd, about 1 year later:

    modern abstract art sofa manufacturer гранит 净水器 混合机 过滤机 DHL快递 保险箱 法兰 法兰标准 牛皮癣 皮肤病 北京快递公司 北京国际快递 传世私服 传奇世界私服 天龙八部私服 天龙私服 网络电话 免费网络电话 假发 补发 织发 植发 上海搬家公司 上海搬场公司 大众搬家 大众搬场 张家界旅游 香港旅游 深圳旅行社 打包机 收缩机 萎缩性胃炎 neoprene laptop bags SEO优化 SEO优化 计量泵 胃炎 胃病 冷水机 冰水机 工业冷水机 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 北京办证 办证 北京特价机票 北京打折计票 北京国际机票 北京机票预定 北京飞机票 北京订机票 北京机票查询 血糖仪 血糖仪 银杏 水培花卉 企业宣传片 空分设备 机电设备安装 代孕 代孕网 代孕 代孕 代孕 试管婴儿 代孕 电话交换机 程控交换机 集团电话 集装袋 混合机混合机 混合机捏合机 捏合机 捏合机导热油炉 导热油炉 导热油炉 反应釜 反应釜 反应釜 回流焊 波峰焊 spherical roller bearing 搬运车 搬运车 电动搬运车 油桶搬运车 堆高车 电动堆高车 半电动堆高车 堆垛车 高空作业平台车 电动叉车 平衡重叉车 前移叉车 电瓶叉车 苗木价格 苗木信息 标牌制作 深圳标牌 儿童摄影 北京儿童摄影 防静电鞋 淘宝刷信誉 威海凤凰湖 威海海景房 大庆密封件 打标机 淘宝刷信誉 TESOL/TEFL国际英语教师证书 英语教师进修及培训 韩国饰品批发 代写论文 代写论文 代写论文 代写代发 论文代写 电源模块 模块电源 X架 超薄灯箱> 易拉宝 展柜制作 代理服务器 游戏加速器 网络加速器 网通加速器 电信加速器 电信网通转换器 电信网通加速器 网通电信互转 网通电信互通 网络游戏加速器 美国VPN代理 美国独享VPN 美国独享IP pvc ceiling panel Spherical roller bearings 天龙八部私服 SEO优化 安全鞋 劳保鞋 防砸鞋 电绝缘鞋 上海安全鞋 上海劳保鞋 江苏劳保鞋 服装软件 服装管理软件 进销存软件 进销存管理软件 服装管理系统 服装进销存软件 进销存系统 进销存管理系统 免费进销存软件 吉林中医 东北特产 打包机 dhl 阳痿 阴茎短小 阴茎增大 早泄 前列腺炎 阴茎增粗 阴茎延长 国际机票 上海国际机票 国际打折机票 国际特价机票 CRM 客户管理软件 客户关系管理 免费客户管理软件 客户管理软件下载 客户信息管理系统 销售管理系统 销售管理 CRM系统 CRM软件 客户关系管理系统 客户关系管理软件 客户管理 客户管理系统 营销管理系统 客户资源管理 销售管理软件 客户资料管理软件 客户资源管理软件 客户信息管理软件 客户资料管理 客户资源管理 客户信息管理 客户资料管理系统 客户资源管理系统 客户管理软件免费版 砂磨机 砂磨机 砂磨机 卧式砂磨机 卧式砂磨机 卧式砂磨机 三辊研磨机 三辊研磨机 三辊研磨机 混合机 混合机 混合机 锥形混合机 锥形混合机 锥形混合机 行星动力混合机 行星动力混合机 行星动力混合机 无重力混合机 无重力混合机 无重力混合机 干粉砂浆设备 干粉砂浆设备 干粉砂浆设备 捏合机 捏合机 捏合机 导热油炉 导热油炉 导热油炉 反应釜 反应釜 反应釜 搪玻璃反应釜 搪玻璃反应釜 搪玻璃反应釜 乳化机 涂料设备 干混砂浆设备 无重力混合机 胶体磨 涂料成套设备 双螺旋混合机 北京婚庆 北京婚庆公司 400电话 办证 呼吸机 制氧机 亚都 亚都加湿器 亚都净化器 亚都装修卫士 饰品批发 小饰品批发 韩国饰品 韩国饰品批发 premature ejaculation penis enlargement 破碎机 制砂机 球磨机 雷蒙磨 雷蒙磨粉机 鄂式破碎机 鄂式破碎机 免烧砖机 加气混凝土设备 反击式破碎机 选矿设备 安利产品 马来西亚留学 网站优化 网站推广 衬布 代写论文 代写论文 代写论文 论文代写 代写论文 代写硕士论文 代写毕业论文 磁力泵 离心泵 化工泵 隔膜泵 螺杆泵 潜水泵 油泵 耐腐蚀泵 泵 水泵 拖链 防护罩 排屑机 塑料拖链 钢铝拖链 水泵 磁力泵 隔膜泵 离心泵 液下泵 自吸泵 多级泵 排污泵 螺杆泵 油泵 化工泵 电动隔膜泵 气动隔膜泵 自吸式磁力泵 氟塑料磁力泵 管道离心泵 导热油泵 深井泵 潜水泵 污水泵 潜水排污泵 深圳装饰 深圳装饰公司 深圳装修公司 特价机票 打折机票 国际机票 机票 新风换气机 换气机 立式新风换气机 风机箱 新风系统 能量回收机 搅拌机 混合机 乳化机 分散机 毛刷 毛刷辊 工业毛刷 刷子 钢丝刷 涂层测厚仪 硬度计 兆欧表 激光测距仪 测振仪 转速表 温湿度计 风速仪 超声波测厚仪 粗糙度仪 噪音计 红外测温仪 万用表 硬度计 万用表 美容院 美容加盟 澳洲留学 澳大利亚留学 什么是法兰 电烤箱 酒店预定 北京酒店预定 北京酒店 离心机 nail equipment nail products nail product nail uv lamp nail uv lamp nail uv lamps uv nail lamp nail brush nail file nail tool nail tip nail gel curing uv lamps lights 万用表 风速仪 红外测温仪 噪音计

  • 123, about 1 year later:

    情趣用品,情趣用品,情趣用品,情趣用品,情趣用品,情趣,情趣,情趣,情趣,情人歡愉用品,情惑用品性哥,情人用品性哥,情趣用品,AIO交友愛情館,情人歡愉用品,美女視訊,情色交友,情人用品性哥,視訊交友,辣妹視訊,美女交友,性愛,嘟嘟成人網,按摩棒,震動按摩棒,微調按摩棒,情趣按摩棒,逼真按摩棒,G點,跳蛋,跳蛋,跳蛋,性感內衣,飛機杯,充氣娃娃,情趣娃娃,角色扮演,性感睡衣,後庭區,SM,潤滑液,情趣禮物,威而柔,香水,精油,芳香精油,自慰,自慰套,性感吊帶襪,情趣用品加盟,情人節禮物,情人節,吊帶襪,辣妹視訊,美女交友,情色交友,成人交友,視訊聊天室,美女視訊,視訊美女,情色視訊,免費視訊聊天,視訊交友,視訊聊天,AIO交友愛情館,嘟嘟成人網,成人貼圖,成人網站,AIO交友愛情館,情色,情色貼圖,情色文學,情色交友,色情聊天室,色情小說,七夕情人節,色情,A片,A片下載,免費A片,免費A片下載,情色視訊,情色電影,色情網站,辣妹視訊,視訊聊天室,情色視訊,免費視訊聊天,視訊聊天,美女視訊,視訊美女,美女交友,美女,情色交友,成人交友,自拍,本土自拍,情人視訊網,視訊交友90739,生日禮物,情色論壇,正妹牆,正妹,成人網站,A片,免費A片,A片下載,免費A片下載,AV女優,成人影片,色情A片,成人論壇,情趣,免費成人影片,成人電影,成人影城,愛情公寓,色情影片,保險套

  • qw, about 1 year later:

    Thanks so much for this! This is exactly what I was looking for

    mirc mırc mırç mirç mirc indir mirc yükle mirc yukle türkçe mirc mirc indir mirc islami sohbet kelebek kelebek script kelebek sohbet kelebek mirc chat çet cet çet odaları sohbet kanalları sohbet odaları kameralı sohbet kameralı chat sohbet eğlence mirc sohbet odaları sevgili arkadaş arkadaş bul arkaraş ara oto araba şarkı sözleri astroloji ikinci el telefon gazete gazeteler günlük gazeteler marifetname bedava domain ücretsiz domain benimurl parça kontör parça kontör radyo dinle bedava blog ücretsiz blog

  • , about 1 year later:

    Victorias Secret Victoria’s Secret Fashion show Victorias Secret Pink Victorias Secret Model Victorias Secret Credit Card Victorias Secret Coupon Code Victorias Secret Lingerie Victorias Secret Fashion Show 2005 Victorias Secret Fashion Show 2006 Victorias Secret Bra Victorias Secret Catalog Victorias Secret Pantie Victorias Secret Online Coupon Victorias Secret Fashion Show 2007 Victorias Secret Girl Free Shipping Victorias Secret Victorias Secret Home Victorias Secret Christmas Victoria’S Secret Pink Dog Victorias Secret Music Victorias Secret Semi Annual Sale Victorias Secret Jobs Victorias Secret Free Shipping Code Victorias Secret Shoes Victorias Secret Thong Victorias Secret Commercial Victorias Secret Promotional Code Victorias Secret Love Spell Victorias Secret Boots Victorias Secret Employment Victorias Secret Reviews Victorias Secret Jeans Victorias Secret Brasil Victorias Secret Bag

  • , about 1 year later:

    情人用品,情人用品性哥,情 人用品,情趣用品,視訊交友,視訊美女,視訊美女,視訊交友網,視訊聊天室,視訊聊天室,視訊 交友網,免費視訊聊天,辣妹視訊,辣妹視訊,情人視訊網

  • dd, about 1 year later:

    徵信社,案件討論,男女專區,法律諮詢,相關新聞,情趣用品,情趣用品,情趣精品,情趣用品,情趣用品,情趣用品,情趣用品,威而柔,自慰套,自慰套,SM,充氣娃娃,充氣娃娃,潤滑液,飛機杯,按摩棒,跳蛋,性感睡衣

    威而柔,自慰套,自慰套,SM,充氣娃娃,充氣娃娃,潤滑液,飛機杯,按摩棒,跳蛋,性感睡衣,視訊交友90739,情人視訊網,情色交友,視訊交友,辣妹視訊,美女視訊,aio交友愛情館,情色論壇,成人論壇,免費視訊聊天,辣妹視訊,視訊交友網,美女視訊,視訊交友,成人視訊,情趣用品,成人聊天室,情趣,情趣,視訊聊天室,視訊聊天,視訊聊天室,情色視訊,情人視訊網,免費視訊聊天室,aio交友愛情館,色情遊戲,寄情築園小遊戲,情色文學,一葉情貼圖片區

  • jj, about 1 year later:

    :-)))) Very interesting! Thanks!!! phone sex phone sex phone sex phone sex phone sex phone sex phone sex phone sex phone sex phone sex phone sex phone sex phone sex phone sex mootzie cosmology edvard munch humorous quotations hundredth monkey brain teasers jillian ann shakespeare quotations bride of frankenstein gettysburg address bill of rights van gogh bowling tips violin books eden prosper julia dreyfus violin bows chess download xslt aviation funny quotes xslt tips gothic abs self hypnosis gothic clothes monique olivia noda amanda roberts somethings happening bgreen68 bfire3 reldeve links psychology hypnosis phonesex phonesex phonesex phonesex phonesex phonesex phonesex phonesex phonesex phonesex phonesex phonesex phonesex phonesex mootzie buffys bedroom blog the great adventure