Mikey Hogarth

Digital Media Development, Code and Opinions

Concrete5 custom theme cheat sheet

conc_header_logo

This is a cheat sheet for setting up a custom theme in the current release of the awesome CMS “Concrete5″ (which at time of writing is 5.5). This assumes that you have a bunch of static html files and you have your design all up and running within a file system. These are the basic steps to go through when you come to “concrete-fying” your site.

If you haven’t checked out Concrete5 yet, you definately should!

This is not meant to be a comprehensive guide, it’s just a quick step-by-step. Assumes knowledge of concrete5, php and basic front end. If anyone finds it useful then great.

These are, in order, the steps I go through to get a basic html template up and running in Concrete 5.

Basic Setup

Put all your html/js/css in a folder under the concrete5/themes folder

Create an additional file called “Description.txt” in that folder, first line is the title of the theme, second line is a short description.

Copy/paste the most “typical” html file in your collection, rename it “default.php”. Then within default.php…
Paste this after opening head tag:
<?php Loader::element('header_required'); ?>
Paste this before closing body tag:
<?php Loader::element('footer_required'); ?>
If you have a copyright line, use this to auto-populate date:
<?php print date('Y') . ' ' . SITE; ?>
Any relative links to stylesheets, replace with this:
<?php print $this->getStyleSheet('css/your_style_sheet.css'); ?>
Any other relative links (e.g. images, javascripts) should have this pasted before the path
<?php print $this->getThemePath(); ?>
Inside the theme folder, create a new folder called “elements” and two blank php files called “header.php” and “footer.php”

Grab all content that is “common to the top” of every page on your site (typically everything down to and including the opening body tag) and paste it into “header.php”

Grab all content that is “common to the bottom” of every page on your site (typically javascripts and the closing body/html tags) and paste it into “footer.php”

Where the header and footer used to be, place the following;
<?php include("elements/header.php"); ?>

If you have a jquery link in your templates, delete it, concrete5 will put one of these in and you can

Create editable sections

Replace global/local areas of editable content with the following (change string for each one);

<?php $a = new Area('Main'); $a-->display($c); ?>
<?php $a = new GlobalArea('HeroText'); $a-->display($c); ?>

Once they’re added, install the theme and check you have it all set up correctly. This is a good time to splat any bugs as common ones will arise at this point. Particularly common ones are;

  • Your CSS styles are conflicting with concrete 5′s css files (this will produce effects like the editable hover block / edit interface looking a bit screwy)
  • Your javascripts conflicting with the concrete5 javascripts. NOTE: make sure you haven’t included two jquerys (check console for errors).

Sorting out the nav

Add all pages in as you want them, then set up the nav. To do this;

  1. Create a folder – (root)/blocks/autonav/templates
  2. Copy the file “view.php” from (root)/concrete/blocks/templates/view.php and put it in your newly created folder
  3. rename the file to something like “header_nav_template.php”
  4. Edit the file to put in whatever custom html you want (the file is very well commented)
  5. Because we don’t really want the user adding or deleting the nav, we can hard code this block into the view using the following (replace with any options you want);


<?php
$bt = BlockType::getByHandle('autonav');
$bt->controller->displayPages = 'top';
$bt->controller->orderBy = 'display_asc';
$bt->render("templates/header_nav_template");
?>

The setup is similar for doing breadcrumb style navs, but you insteadyou are overriding “concrete/autonav/templates/breadcrumbs” (which you copy into the same folder as above). Then to hard code this into your view you use;


<?php
$autonav = BlockType::getByHandle('autonav');
$autonav->controller->orderBy = 'display_asc';
$autonav->controller->displayPages = 'top';
$autonav->controller->displaySubPages = 'relevant_breadcrumb';
$autonav->render('templates/custom_breadcrumb');
?>

Set up your various page types

Copy/paste your “default.php” page, rename it to each of the page-types you want within your site, e.g. “2-column.php”, “home.php”. You can make any ammendments to each of these at this stage (e.g. change markup, any additional editable content areas and so on).

Once you have done this for all your templates, you can pretty safely delete any remaining html files within the theme folder.

If you uninstall/reinstall your theme, concrete5 will see these new files and will then add in the nessecary database rows to get them all set up.

Bubblr – JQuery bubbles plugin

The bubblr JQuery plugin allows you to add a bubbling animations to any canvas element. It allows you to specify options such as the number of bubbles, the colour/background colour of the canvas (including “transparent”) and the size of the bubbles.


Static screenshot of the bubbles in action

Applications for this plugin include;

  • Add lifelike movement to elements such as drinks, fish tanks and aquatic scenes.
  • Create other particle effects such as smoke, fire and starship warp cores.
  • Send your users into a hypnotic trance – nobody can resist the power of bubblr!
  • Works on all HTML5 compatible browsers, including both robot and fruit-based tablets and phones.

Full source code is available for download here: https://github.com/mikeyhogarth/bubblr

Demo of bubbr-y goodness available here: http://bubblr-demo.heroku.com/

Licensed under GPL and MIT.

Passing the time in Tanzania

Just got back today from a life changing holiday in Tanzania. Lots of long road trips to get to the various regions, and here’s how we passed the time :)

The game is “Africa Films” (or #africafilms if you like!) and these are our greatest hits.

  • Educating Cheetah
  • Beauty and the Wildebeast
  • Hyena Noon
  • Hang ‘em Hyrax
  • The Impala Strikes Back
  • Fight Cub
  • Honey badger, i shrunk the kids
  • Bulletproof Monkey
  • Elephantasia
  • Star Trek 2: Giraffe of Kahn
  • Man in the lion mask
  • Snow White and the seven Dwarf Mongooses
  • Dik-dik Tracy
  • Eland before time
  • Lovebirds Actually (with Hugh Grant-gazelle and Emma Thomson-gazelle)
  • Blue Vervet
  • Look who’s storking
  • Serengettysburg
  • Arusha Hour
  • Warthog Day
  • Memoirs of Acacia

Anyone who has any other suggestions, feel free to submit them in the comments :)

Escape html fractions in rails

One requirement of a project I’m undertaking at the moment is that the user should be able to enter ingredients into a CMS like this;

1/2 kg sugar

but that when it renders it should convert their 1/2 into the “half” html escape sequence, and similarly for other fractions. There doesn’t appear to be a gem out there that does exactly this, but there was a really nice snippet that provided a good base. With that, it was just a case of using a regex to pull out the fraction characters and a gsub to replace them with an escape sequence. The following therefore went into the application helper file;

#Accepts string and looks for instances of number/number, then attempts to parse those into
#html escape sequences.
def escape_fractions string_with_fractions

   #snippet inspired by http://snippets.dzone.com/posts/show/2323
   string_with_fractions.gsub(/\d\/\d/) do |match|
   case match
      when "1/2" then '@amp;frac12;' # One half
      when "1/4" then '@amp;frac14;' # One quarter
      when "3/4" then '@amp;frac34;' # Three quarters
      when "1/3" then '@amp;#x2153;' # One third
      when "2/3" then '@amp;#x2154;' # Two thirds
      when "1/5" then '@amp;#x2155;' # One fifth
      when "2/5" then '@amp;#x2156;' # Two fifths
      when "3/5" then '@amp;#x2157;' # Three fifths
      when "4/5" then '@amp;#x2158;' # Four fifths
      when "1/6" then '@amp;#x2159;' # One sixth
      when "5/6" then '@amp;#x215A;' # Five sixths
      when "1/8" then '@amp;#x215B;' # One eighth
      when "3/8" then '@amp;#x215C;' # Three eighths
      when "5/8" then '@amp;#x215D;' # Five eighths
      when "7/8" then '@amp;#x215E;' # Seven eighths
   else match
   end
  end.html_safe
end

NB You’ll need to replace all @ symbols with & – couldn’t for the life of me work out how to stop wordpress escaping them!

Anyway, this allowed the view to do things like this;

<% @recipe.ingredients.each_line do |ingredient_line| %>
<li><%= escape_fractions ingredient_line %></li>
<% end %>

Comma seperated list of links in rails

One very common requirement of web applications is to have a comma-separated list of links display in the browser (usually things like categories or tags). This is traditionally quite annoying for programmers because the usual approach is to iterate through an enumerable object and build up a string, then deal with the messy business of shaving off that inevitable “last comma” so your links don’t end up looking like this;

Games, Movies, Videos,

As always, such things are much easier in ruby. In the case of a rails application, if you place the following code in your application helper file;

  
  def comma_seperated_links_for(list)

    raise TypeError, "parameter must be an array" unless list.is_a? Array 
    return if list.count == 0

    list.collect do |item| 
      raise TypeError, "items must respond to 'name'" unless last_item.respond_to? :name
      link_to(item.name, url_for(item)) 
     end.join(", ").html_safe
  end

You can lean that up by removing all of the “raise” calls, I only include them here to demonstrate the limitations of the implementation. Not only is this a slick and efficient implementation, it also means you get a huge dose of Knuthian readability straight into your views :)

   <%= comma_seperated_links_for @product.categories %>

Clash between active admin and friendly id

In my opinion two of the most indispensable gems, active admin and friendly id, don’t work together out of the box! Thankfully, a really neat solution does exist and was providedby StackOverflow user Thomas Watson (who after a bit of internet stalking I tracked down as residing at http://justaddwater.dk/) as an answer to this question. Personally I think this guy deserves a medal!

Here’s a link to Thomas’s solution, and it works perfectly!

PDF generation in rails 3 with prawn

Firstly, as always, there is a fantastic Railscast by Ryan Bates which explains Prawn perfectly. Having said that, there are a few things that it doesn’t mention that you need to do in order to use prawn in Rails 3. The path to getting this working is as follows;

#First install prawn on your system (lose the sudo if you're running under RVM)
sudo gem install prawn

#install the prawnto plugin
rails plugin install https://github.com/prior/prawnto.git

#add prawn to your Gemfile
gem "prawn"

After this, you should be able to do everything Ryan does in his railscast :)

Switching to mongrel in rails 3

Dead easy with a few hiccups if you’re using newer ruby versions. First install the mongrel gem;

> gem install mongrel --pre

The problem I had (and later overcame) was in not adding in the --pre option into the install – turns out the current stable doesn’t play very well with newer ruby versions. This is likely to be fixed at some point, but this’ll get you through today :)

After that, just add the following to your Gemfile;

gem 'mongrel'

then just bundle install and rails will use mongrel as the default web server.

Submitting a form using Jquery ajax

This code will work for any scenario where you want to post back a form to the server asynchronously, and then render a response. The use of the “on” keyword here (JQ1.7 and above only) allows the event to stay attached to the element even if it’s posted back later. The scenario I used this was in an “add comment” type form, where the form would fade out on submit, and then fade back in with either a message stating that the comment was received successfully, or alternatively would re-display the form with error messages if it wasn’t.


    $(document).ready(function() {       
    
        $(document).on("click", "#formSelector" , function() {
            var $form = $(this).parents('form');

            $.ajax({
                type: "POST",
                url: $form.attr('action'),
                data: $form.serialize(),
                error: function(xhr, status, error) {
                    //Actions to take on error
                },
                success: function(response) {
                    //Actions to take on success
                }
            });

            return false; //This stops actual postback (some browsers will still try)
        });
    });

Creating your own attr_accessor in Ruby

When going through Ruby 101, you won’t need to do much research before you come accross the use of the attr_accessor methods. There are several flavours of this;

attr_accessor gives you a getter and a setter
attr_reader just gives you a getter
attr_writer just gives you a setter

Here’s a code example of this functionality being used;

class Person
  attr_accessor :name, :age
end

#above class definition enables the following
p = Person.new
p.name = "Mikey"
p.age = 30
puts p.name

Magic. It’s almost like you’ve somehow managed to add two more methods to the person class without defining them. Well, it turns out that this is exactly what you have done! For anyone who is not used to dynamic programming languages (and I include myself in that list) this can be a really tricky point in the learning curve. This sort of functionality is used all the time in ruby, and not only within the context of attr_accessors – The Rails framework, for example, uses dynamic code to allow you to add very complex functionality to your ActiveRecord classes with a single line of code.

If you are anything like me, then you can’t just take the fact that it works for granted! I needed to know *exactly* how this sort of thing is possible! This post will clear up exactly how this attr_accessor magic works by showing you how to make your own version of the same functionality.

Dynamic code is created using a series of “eval” methods which the ruby language makes available to you. There are several flavours (eval, instance_eval, class_eval, module_eval) – the one we’ll be using here is class_eval, which you basically use to add code to a class. As we will be trying to create a method that will be accesible from all classes, we will need to add our code to the Class class (not a typo!). This is going to get a bit headswimmy, so I’ll just go ahead and show you the code itself then discuss it below.

class Class
  #firstly, the * decoration on the parameter variable
  #indicates that the parameters should come in as an array
  #of whatever was sent
  def mikeys_attr_accessor(*args)

    #We simply iterate through each passed in argument...
    args.each do |arg|
      
      #Here's the getter
      self.class_eval("def #{arg};@#{arg};end")
      
      #Here's the setter
      self.class_eval("def #{arg}=(val);@#{arg}=val;end")                      
                      
    end
  end
end

The above code allows a new class to be defined as follows;

class Person
  mikeys_attr_accessor :name, :age  
end

Which in turn allows you to write code like this;

person = Person.new
person.name = "Mikey"
person.age = 30
puts person.name
puts person.age

A lot was going on in the first code example, but the rest of it functions exactly as you would expect attr_accessor to function. The focus here will therefore be on the first bit of code. So it all starts off pretty basically, we are able in ruby to extend any class simply by using the class keyword. We then add the method “mikeys_attr_accessor” to it, using a bit of ruby syntactic sugar to allow this method to receive any number of arguments. It’s worth pointing out that we should really check that these arguments were symbols, but as this is a simple example I’ll skip that part.

Next we iterate through each argument and make two calls to the “class_eval” method. The message we send to this is basically just an interpolated string representing the code we want included in our object. Yes, I did say object – you might raise the question at this point as to why I’m using the word “object” when we are clearly adding a method to a class. You might also question the presence of the word “self” before the “class_eval” call, surely this would mean that we have somehow managed to create an “instance” of a class?!

This was pretty much the point, while learning Ruby, that I lost cabin pressure.

class Person
end

Person.class
=> Class

The capital letter at ths start of Person indicates that it is a constant. Person is constant instance of the Class class. As you’ve instantiated the Class class in your Person class, you need to use “self” on the class eval to make sure that the class_eval method is talking to the Person instantiation of the Class class. You may need to read the previous sentence a few times before it sinks in (if you feel your ears starting to bleed, contact your GP immediately).

A better question is that, if this is the case, why is class_eval used instead of instance_eval? the short answer to that is that it has to do with scope and context. If you are interested in learning a bit more about metaprogramming, i found the following question over on stack overflow to be incredibly useful. Lots of great links from the respondants.

http://stackoverflow.com/questions/788689/ruby-metaprogramming-online-tutorial

Follow

Get every new post delivered to your Inbox.

Join 445 other followers