Theme support

Posted on Sat Jul 28 @ 21:50:20

Today I managed to implement a simple theme support for my blog. The result is that now the site has a new look and feel.

The implementation was simple. First I overwritten the template_path class method of ActionController::Base class in my ApplicationController like so:


    class ApplicationController < ActionController::Base
        def self.template_root
          theme = Preference.get('site_theme')
          if theme.size > 0
            "#{RAILS_ROOT}/themes/#{theme}" 
          else
            "#{RAILS_ROOT}/app/views" 
          end
        end
    end

After that I also wrote two helpers that compute the correct path to javascripts and stylesheets for the selected theme. In app/helpers/application_helper.rb I wrote these two methods:


    def theme_stylesheet_link_tag(*styles)
      theme = Preference.get('site_theme')
      if theme.size > 0
        styles.collect do |style|
          source = compute_public_path(style, 
                    "themes/#{theme}/stylesheets", 'css')
          tag("link", {"rel" => 'stylesheet', 
              "type" => 'text/css', 
              "media" => 'screen', "href" => source})
        end
      else
        styles.collect do |style|
          stylesheet_link_tag style
        end
      end
    end

    def theme_javascript_include_tag(*scripts)
      theme = Preference.get('site_theme')
      if theme.size > 0
        scripts.collect do |script|
          source = compute_public_path(script,
                   "themes/#{theme}/javascripts", 'js')
          content_tag("script", "", { "type" => "text/javascript",
                      "src" => source})
        end
      else
        scripts.collect do |script|
          javascript_include_tag script
        end
      end
    end

The Preference.get(‘site_theme’) is a simple implementation of preferences I found looking through the simplelog code. That part of the code can be made more general but for this site it sufficed.

And that was it. Now you can add theme views and layouts in #{RAILS_ROOT}/themes/#{theme} folder and assets in #{RAILS_ROOT}/public/themes/#{theme} folder.

I was aware of theme_support plugin but it needed to be patched to work with rails 1.2.3 and I needed a simpler solution.

I hope someone will find this helpful. I will make a plugin out of this and make it available to the general public.

One last thing. When you change the theme you need to restart your rails application.

Enjoy!

Posted in Rails, 2 Comments Comments

Comments

CROATIA derishte :D on 29 Jul at 17:07:12

jej :D shema dizajn~ kiwiiii~~~~~~~

CROATIA Denis Brulić on 01 Aug at 15:09:54

Green is nice!

COMMENTS ARE DISABLED