Category: Programming

Linux, Laravel, PHP. My notes and mini-guides regarding development-related things.

  • 📂

    Laravel Blade push and stack

    Laravel’s blade view compiler is second to none. I’ve used a couple of different templating engines and blade is by far my favourite.

    Including Partials

    The way in which we include partials of views within our main views is as follows:
    @include(‘partials.my-first-partial’)
    It will inject that partial’s content in the specified place.

    Defining Sections

    Within our views, we define “sections” with the following syntax:

    @section(‘section_name’)
    
        The section’s content within here
    
    @stop

    And we can define as many sections as we need for our project.

    When the same section is used in multiple places within one compilation

    Imagine we have master template file as such:

    // layouts.main.blade.php
    <!doctype html>
    
    ...
    @yield(‘partials.form’)
    ...
    
    @yield(‘custom_scripts’)
    
    

    Let’s suppose we have the following layout template that extends our main layout one and is including three partials. This example is a form template including its various inputs from separate partials. For my own website I have a different form for each of my post types and so I have the inputs in separate partials for easy reuse.

    // partials.form.blade.php
    @extends(‘layouts.main’)
    
    <form>@include(‘parials.form-title’)
    @include(‘parials.form-content’)
    @include(‘parials.form-tags’)</form>
    

    Let’s next suppose that in a couple of those partial input views you need to inject some custom scripting. This is a slightly contrived example, but it will illustrate the point.

    // partials.form-content.blade.php
    <textarea class="content" name="content"></textarea>
    
    @section(‘custom_scripts’)
    // dummy javascript as example
    $(‘.content’).doSomething();
    @stop
    
    // partials.form-tags.blade.php
    <select class="tags" name="tags">
    <option value="tagone">Tag One</option>
    <option value="tagtwo">Tag Two</option>
    <option value="tagthree">Tag Three</option>
    </select>
    
    @section(‘custom_scripts’)
    $(‘.tags’).doSomethingElse()
    @stop
    

    Now, when the form page gets compiled, only the first occurrence of the ‘custom_scripts’ section will be included.

    So what if you needed to be able to define this section in chunks across partials?

    Introducing Blade’s Push & Stack directives

    To give this functionality, Laravel does in fact have two little-known directives called ‘push’ and ‘stack’.

    They allow you to ‘stack up’ items across partials with the ‘push’ directive, which can then be echoed out together with the ‘stack’ directive.

    Here’s the above form example but with ‘push’ and ‘stack’ used in place of ‘section’ and ‘yield’.

    // layouts.main.blade.php
    <!doctype html>
    
    ...
    @yield(‘partials.form’)
    ...
    
    @stack(‘custom_scripts’)
    
    
    // partials.form-content.blade.php
    <textarea class="content" name="content"></textarea>
    
    @push(‘custom_scripts’)
    // dummy javascript as example
    $(‘.content’).doSomething();
    @endpush
    
    // partials.form-tags.blade.php
    <select class="tags" name="tags">
    <option value="tagone">Tag One</option>
    <option value="tagtwo">Tag Two</option>
    <option value="tagthree">Tag Three</option>
    </select>
    
    @push(‘custom_scripts’)
    $(‘.tags’).doSomethingElse()
    @endpush
    

    This will now compile all uses of the @push(‘custom_scripts’) and echo them out as one wherever you call @stack(‘custom_scripts’)

    When I was shown this technique by a mate at work, it blew my mind.

    Have fun.


  • 📂

    Bypassing Laravel’s CSRF Middleware on selected routes (from 5.1)

    Laravel does a great job at protecting us from cross-site request forgeries – or C.S.R.F. for short.But sometimes you may not wish to have that layer present. Well with Laravel 5.1 you can very easily bypass this middleware, simply by populating an array in the following file:

    app/Http/Middleware/VerifyCsrfToken.php

    Within this class you can add a protected property — an array — called $except, which will tell Laravel to use this middleware except for the ones you specify here.

    A complete example could be:

    protected $except = [
        'ignore/this/url',
        'this/one/too',
        'and/this',
    ];

    So for those three URLs, the CSRF middleware would be skipped.


  • 📂 ,

    My IndieWeb Setup

    Please note: This is now out of date somewhat

    This post is an outline of my IndieWeb setup. I describe some of the key plugins I have installed as well as third party services I use. All of which play nicely together for the IndieWeb.Built with WordPressMy personal site is built using WordPress and is a completely custom-built theme. WordPress?—?with its plethora of plugins and diverse, active community?—?provides one of the best platforms from which to build an IndieWeb site today – outside of rolling your own. When I first heard about the IndieWeb and found myself wanting to implement its principles on my own site, I went ahead and installed a plugin I was recommended?—?the IndieWeb Plugin?—?which links to a collection of other plugins that implement certain functionality to tie into those IndieWeb principles.Plugins I have installedYou don’t have to limit yourself to only the plugins I list here?—?I have just listed the ones that I myself have in use in regards to IndieWeb.IndieWeb PluginThis plugin, once installed, provides links to the recommended IndieWeb plugins?—?some of which I have listed below?—?that will help bring you into the IndieWeb. I have also provided direct links to the plugins themselves, or you can search in your admin area’s new plugin interface. I haven’t described them all yet as I am not 100% on what some of them do. As I gain an understanding of others I use, I will include them below. The ones that I have described below are the ones I actively use and understand what they do for me. Download the IndieWeb PluginNextScripts : Social Networks Auto-PosterThis is a great plugin for easily syndicating content out to many third-party silos. I use a custom fork of it with editsThe plugin creators have very kindly added in my code edits to allow twitter replies that create those tweets as replies within the Twitter timeline. Social Networks Auto-Poster?—?or SNAP for short?—?has a flexible way in which to template how and what to share to each silo when posting your content. For example in a small note you may send the full text content only, however for an article you have written you may want to send the post title and permalink. Download the SNAP PluginRel-Syndication for WordPressThis plugin works beautifully with the Social Networks Auto-Poster plugin. It will grab the SNAP plugin’s syndication data for a post, and append a list of links to that post’s content. It will also include the necessary microformats2 meta data in the links of those syndicated copies. Download Rel-Syndication for WordPressWordPress Webmention PluginThis sets up webmention support on the site. It allows me to receive webmentions and automagically creates them as comments to those posts. It will also parse the post content for posts I write for any links contained within, and send webmentions to those links. Download WordPress Webmention pluginIndieWeb Custom TaxonomyThis plugin adds an extra semantic layer to posts. It allows you to categorize your posts as being one of the following: “Bookmark”, “Favorite”, “Like”, “Reply”, “Repost” and “RSVP”. All of which are actions that are found on social networks. It also allows you to save a URL to which you may be replying to. The plugin will then pull in that URL to give a preview of the link with the post content. This shows the context to which your post content may be replying to. Download the IndieWeb Custom Taxonomy PluginWordPress Semantic LinkbacksWhen you receive webmentions* from a site?—?or from Bridgy if you use that (see below)?—?then those comments are added to the site. What the semantic linkbacks plugin does is generate semantic comments using microformats2. *Please Note: you will need to have the WordPress Webmention plugin installed for this plugin to recognize Webmentions. See above. Download the Semantic Linkbacks pluginOther Tools I useBridgyBridgy is absolutely bloody fantastic. It is a web app built by Ryan Barrett and automatically polls a number of third-party silos?—?whichever ones you choose to connect?—?and pulls in any links to your website and any new responses to posts you have sent. Once it pulls in links and responses, it will send them over to your website as webmentions. The WordPress Webmention Plugin?—?mentioned above?—?knows exactly what to do with them. There are a couple of configurations that you may need to do also?—?at least these are what I needed to do. Firstly when bridgy finds replies to a tweet that originated from your site it will need to know where that original link is on your website. For example if you just sent twitter a note with no links back, bridgy will need to look on your site for that original message. But how does it know where the post is? It looks for the post that has, within it’s h-entry markup, the syndication link to that twitter copy. If you are using the Rel-Syndication Plugin for WordPress, then your content should already have the syndication links appended to them. One thing I had to also do was to add a “feed” meta link into my site’s header, in order to tell bridgy where those links could be found on my site (as they were not on my homepage at the time). And that’s my IndieWeb setup. Like I said before, there are some other plugins that were recommended from the IndieWeb plugin. However I have not included these here as I am not yet confident in describing those just yet. Any questions about this setup or any other IndieWeb queries please ask. I’ll do my best to help.


  • 📂

    WordPress “Must Use” Plugins Directory

    The Issue

    I wanted to build a site with some custom post types, taxonomies and the like. But what if somebody who has used my theme decided to try another theme later on? What guarantee do they have that those custom post types will be recognized by a future theme?

    None — that’s what.

    WordPress obviously has its plugin directory, which is designed for adding in pieces of functionality that should span across themes. But what if these are essential to the working of the site due to custom post types, taxonomies or shortcodes?

    Either it can be a plugin — which could be accidentally deactivated, or added to the theme’s functions.php — which would need copying over to any future theme.

    A Hidden Gem of a Solution

    Well it turns out that there is a third option — a way for WordPress to auto load essential plugins irregardless of the theme being used. Simply by creating a directory in the ‘wp-content’ folder called ‘mu-plugins’ — which stands for “must use plugins” — and adding plugins as you would into the regular plugins folder, they will be auto loaded with any theme and just work.

    These ‘must use’ plugins will then be viewable in the plugin admin page, in a new option called ‘must use’ — grouped with the other plugin page navigation items, ‘All’, ‘Active’ and ‘Inactive’.

    ‘Must use’ plugins can’t be deactivated in the admin — creating a nice separation of essential plugins for a particular user.

    Thanks to Justin Tadlock for this piece of info.


  • 📂

    WYSIWYGs will kill us all

    So okay, maybe they wont literally kill us all, but you’ve got to admit — they can be pretty damn annoying. At least with ones I have used.

    I’m not dissing wysiwygs — just what they get used for.

    Firstly let me just say that I use a wysiwyg editor on my own blog and it does exactly what I need it to. I type text and it saves that text. I click to add a link and it adds a link. Brill!

    For a blog, where writing long posts with the odd link and / or bolding of text, a wysiwyg really is great. But what I don’t believe in is using a wysiwyg for anything more than that.

    Let me explain.

    With a standard WordPress install, when you write a post or page, the content from the wysiwyg is spat out by the function the_content(). This displays all that content in one block within the page. Of course WordPress is — at its roots, a blogging platform (and a damn good one) so the ease of writing and publishing has always been at the forefront.

    But what if our content is more than just a blog post? What if it’s an album or film review? Or specifications for a car? If we bundle all of the content into one block then we are a stepping away from what we need most nowadays, which is structured content.

    The need for Structured Data

    The need for structured data these days is more important then ever. With the whole multi device landscape, a site’s content needs to be able to display beautifully whereever it is viewed. We need to be able to control as much of the content in as much of a modular way as possible. Also, as a result of making content more modular, it means it can be a lot easier to group and sort that content.

    For example, if we have a database of 500 albums with all of the content for each album in its own single block of content, it makes it extremely difficult to categorize those into various artists or genres. Whereas if it was set it up in a way that has separate fields for each content chunk — an artist field; a genre field; etc — then those albums could be easily sorted and categorized.

    Karen McGrane gave a fantastic talk at An Event Apart, Boston in 2012, where she talked about the TV Guide who made a wise decision about their content structure back in the 1980s. She talked about how the TV Guide wrote out three different descriptions of the same programmes — One small, one medium and one long. This was before TV on demand or Tivo, where now that sort of structured content is invaluable for use across different devices and contexts.

    I recommend you watch the video, but I wanted to include a great quote from that talk here:

    …a clean base of presentation–independent, well–structured content that you have designed, from the start, with the intent that you may want it to go out and live on a wide variety of different platforms. In fact you know from the beginning this content is going to have to live in a variety of different places…

    Karen McGrane An Event Apart, Boston, 2012

    Example – content for a music album

    All the content for an album in one chunk:

    <-- Output Html of the_content() in a wordpress site --> 
    <p>This Train features 12 songs from the angelic, sometimes haunting, voice of Chrysta Bell. It was produced by David Lynch and features songs written by them both, including the track 'Polish Poem' from the film 'Inland Empire'.</p> 
    <p>Artist: Chrysta Bell</p> 
    <p>Produced by : David Lynch</p> 
    <p>Release Date: September 29, 2011</p> 
    <p>Tracklisting:</p>
    <ol>
    <li>This Train</li>
    <li>Right Down To You</li>
    <li>I Die</li>
    <li>Swing With Me</li>
    <li>Angel Star</li>
    <li>Friday Night Fly</li>
    <li>Down By Babylon</li>
    <li>Real Love</li>
    <li>Bird of Flames</li>
    <li>Polish Poem</li>
    <li>The Truth Is</li>
    <li>All the Things</li>
    </ol>

    So while the above html code is okay, it doesn’t allow for much flexibility.

    What happens if — in a few years — the website gets a complete redesign? Imagine there are 500 albums in the site’s database. Well then we’ve got a problem. We can have a lovely new shiny design but the bulk of the content is already set in stone somewhat.

    In the example above we have the track listing below the review. What if we wanted to flip that? Or better yet, what if the new design wanted the track listing removed? What do we do then? Use regular expressions on the html to remove the track listing from the content?

    No.

    Also, as mentioned in Karen McGrane’s talk, the content should be able to live in a variety of different places. What happens if the content is viewed through a smart watch, or internet fridge? Will we want all of that content handed to us in one chunk?

    Probably not.

    Maybe we want to display just the Album title and artist with the option of loading in the track listing if needed.

    In the music album example above, we can see sensible chunks of content that could be easily separated into sensible content chunks:

    • Track Listing
    • Review / Description (perhaps differing versions for use in different contexts?)
    • Producer
    • Artist
    • Title
    • Release Date

    Using separate input fields for each of these chunks, means that each part of the content is individually available and much more flexible in how and where this content can be displayed.

    WordPress has custom fields that can be entered on a per page/post basis, as well as the ability to add custom post types. No doubt other CMSs have similar options available — I’m just not very clued up on those ones.

    The use of these custom fields is definitely a step in the right direction, but what we need is for CMSs to be more content-modular at their core. Like I said before, I’m not clued up on CMSs — other than WordPress and OpenCart — so please don’t hunt me down and shoot me in the face if there are indeed CMSs out there already like this.

    And if there are please let me know of some good ones.

    Tar!

    Inspiring this post

    This post was originally going to be me snivel–bitching about wysiwygs. But I heard this podcast on the web ahead, which talks about content structure in great depth and it got me thinking about it in more detail than my initial post. The podcast also mentioned that talk by Karen McGrane.

    On the evening of me writing this post, before publishing the following day, I travelled down to Milton Keynes Geek Night and saw five fantastic talks.

    One of those talks was by Relly Annett-Baker called ‘Future Perfect Tense: creating good content for an imperfect web’. A lot of what Relly was talking about was stuff I had been thinking about that day — so that was nice.

    I will link the recording of the talk when it goes online as it is well worth a listen.


  • 📂

    HTML 5: Omitting unnecessary speech marks

    In my last post I described how it is possible to cut down on your HTML filesize and save some time in your coding by omitting optional closing tags.

    As a follow up to that post I thought I’d also describe another process to save even more on your filesize and a little bit more time still.

    Please note however, these examples i’m describing are really micro-optimizations. For every project you make to be the best that it can be, I would strongly recommend looking into combining your scripts into one single file and minifying it. Minifying your CSS can also go a long way to improving speed. Those techniques, as well as others, are a seperate issue but are definiately worth your time in learning.

    Back to the speech marks

    A lot of us developers, me included, have a habit of wrapping up our attributes in speech marks, whether single or double, as in the following example:

    <head>
      <meta charset="utf-8">
      <title>Example Title</title>
      <link rel="stylesheet" href="css/style.css">
    </head>

    The truth is, however, that in most cases you can leave the speech marks out completely, as in the following example:

    <head>
      <meta charset=utf-8>
      <title>Example Title</title>
      <link rel=stylesheet href=css/style.css>
    </head>

    The browser will still render that correctly, and if you view the page source with the Chrome dev tools ‘inspect element’, you’ll see that the speech marks have in fact been put in for you!

    Most Cases you say?

    There is one situation where you will still need to use speech marks. This is when attributes have more than one value, or includes any white space. For Example:

    <section>
      <span class="main-class secondary-class"></span>
      <img class=section-image src="images/image name with spaces.jpg">
    </section>

    So as a rule, when declaring attributes on html elements, you can omit all speech marks where there’s no white space contained. This is because the attribute ends when it hits the white space. I hope this helps you all to add an extra little bit of optimization into both your workflow and the size of your code.

    If you have any of your own tips for code optimization, please share it in the comments section below. Thanks!


  • 📂

    HTML5: On removing optional closing tags

    Firstly, an example of some html…

    <article>
    
    
      <p>Once upon a time there was a web programmer.</p>
      <p>He found that he wanted to cut down on his html filesize.</p>
      <p>He came up with a list of ideas. They were as follows:</p>
    
    
      <ul>
        <li>Minifying his code</li>
        <li>Cutting out content, (unacceptable!!!).</li>
        <li>Remove optional tags, speech marks, etc...</li>
      </ul>
    
    
      <p>On writing the last item in the list, he exclaimed, <em>That's amazing</em>, now to tell others...</p>
    
    
    </article>

    Lovely and semantic. Now, there’s nothing at all wrong with what I’ve written above. This article is all about showing you how there are certain things in your HTML that can be left out, without breaking any part of it.

    You can actually omit many closing tags and still have it render exactly how you planned.

    The example above, after removing optional closing tags:

    <article>
    
    
      <p>Once upon a time there was a web programmer.
      <p>He found that he wanted to cut down on his html filesize.
      <p>He came up with a list of ideas. They were as follows:
    
    
      <ul>
        <li>Minifying his code
        <li>Cutting out content, (unacceptable!!!).
        <li>Remove optional tags, speech marks, etc...
      </ul>
    
    
      <p>On writing the last item in the list, he exclaimed, <em>That's amazing</em>, now to tell others...
    
    
    </article>

    The elements removed:

    Paragraph closing tags can be omitted, because when the next one begins it knows that the last one has finished. Same with the list items also. Each list is begun with its <li>. But you’ll notice other closing tags have been kept.

    The elements remaining:

    The article still needs to be closed, as the browser will otherwise think the article is ongoing. The </ul> has also been kept, as it wraps the list, and stops the last list item from continuing onwards. And lastly in the example above, the </em> has remained, simply because, if left out, will continue to emphasize the rest of the paragraph.

    Common Errors to be aware of:

    There may be times when you will omit a closing tag, but find it may mess up your code. For Example:

    <article>
      <h1>The heading is as expected. Yay!
      <p>But the paragraph inherits styles from the <h1>, boo!
    </article>

    The above happens, quite simply, because the browser doesn’t know that the <h1> should close. So as a result the paragraph is treated as though it is ‘wrapped within’ the <h1></h1> tags. The <h1> in the example above is closed by the browser, when it reaches the end of its parent continer, the <article> And so ends up rendering as the following:

    <article>
      <h1>The heading is as expected. Yay!
        <p>But the paragraph inherits styles from the <h1>, boo!</p>
      </h1>
    </article>

    Combating this, however, is easy. See the following:

    <article>
      <header>
        <h1>The heading is now contained within both header tags that we close in the code...
      </header>
      <p>...and so now the heading styles wont bleed into this paragraph as they are contained in the <header>
    </article>

    By way of summary

    At first it can feel odd omitting these optional closing tags, but it will, in the long run, save you both time and those precious bytes. You just need to make sure you pick your times carefully. Generally, the rule I try to stick to is: if its a container with more than one type of child element (ie. article, section, div, nav etc.) close them off in your code. But if they are single entities, such as paragraphs, headings(of same number), lists etc, that are immediately preceded by the same tags, and have no differing siblings, omit the closing tag.

    It will take a bit of getting used to, but if you nest your code well you will quickly begin to notice where you can omit closing tags.

    Developer inspect tools can help

    I am a huge fan and regular user of the chrome developer tools. you can use its ‘inspect element’ feature to test out your code to see where the tags are being closed by the browser. Just write a paragraph without the closing tag and view it in the inspector. When you see it in the flesh and get used to how the browser renders your code, it will give you more confidence to omit those optional tags.

    In Google Chrome, right click any part of the web page, and you should see the option to ‘inspect element’ towards the bottom.


  • 📂

    CSS… how to use sass and compass: Part Two

    Please note: for the sake of brevity, when using sass and compass, I refer to them both as compass.

    Following on from our previous tutorial, I would like to introduce you to @import. @import is a css feature that will allow you to import stylesheets into one another. For example:

    @import "normalize.css"; 
    body{
        background:lightblue;
        width:1000px;
        margin:auto;
    }

    This will bring in ‘normalize.css’ from the same folder as the stylesheet itself, and then apply the body properties.

    With this, however, it will grab each @import on page load and add unnecessary time to your page download speed. In this part of my compass tutorial, I will show you how to incorporate @import and use compass to compile them all into one stylesheet during production.

    How styles get compiled

    Remember from the last part of the tutorial when we changed the style.scss file, and it updated our style.css one? Well we could in fact have any number of files, with different names, and they would each update in the same way. So if you had a base.scss, it would compile to base.css, typography.scss would update typography.css, and so on. You need not create the .css version either, as compass will do this for you automatically if it can’t find one when it compiles.

    The way in which it compiles is defined in the config.rb file. As mentioned in the previous post, I highly recommend you set it to ‘:compressed’ before uploading to your server, as this will improve your page loading speed. The reason for this is that it removes any and all comments and white space.

    Example Stylesheet setup

    Below I have listed the default structure of my stylesheets. Create them as .scss files in your sass folder and please note the underscores, as these are needed. You wont be needing any .css versions. The only css file you will need is style.css.

    I recommend you save a copy of the whole project directory when you have these stylesheets setup. That way you will have a nice starting off point for each of your projects.

    • _normalize.scss
    • _helpers.scss
    • _print.scss

    Remember that stylesheet I advised you to temporarily save to your desktop? Well we are now going to bring that back in. If you open it in your code editor, you will see it is split into three main areas (not including the media queries part). The main code up top is the normalize. Then you have useful helper classes, and finally a set of print styles.

    Copy and paste each part of the stylesheet into their respective .scss files.

    Now re-open your style.scss and delete any previous code out, and write the following:

    @import "normalize";
    @import "helpers";
    @import "print";

    Save it. Notice how I have not included the underscore or the ‘.scss’ extension, as these are not required when importing them.

    If it isn’t already running, start compass off watching your project as shown in the previous part. Compass should detect the changes to style.scss straight away and compile to its css equivalent. So now on re-opening style.css, you should see how normalize, helpers and print have all been pulled in from their imports on style.scss

    What this now means is that you could theoretically split your styles into as many separate sheets as your wanted. As long as you remember to @import them into style.scss, then compass will see any changes to any of them and compile them all together into the one style.css. See, I told you they were awesome.

    I encourage you to go now and experiment with splitting up your own stylesheets into manageable chunks. You will soon find a balance that suits your own tastes.

    Thank you for reading the tutorials this far. I hope these first two parts have given you a good start with using sass and compass, although I did say I’d only refer to them as compass… Darn it! Oh well.

    I realize this isn’t the most exciting of the features available to them. After all, I haven’t even mentioned mixins or even nesting (coming up in next part), but for me at least this has been the most indespensible of the features I’ve learnt so far.

    I hope this helps you get up and running with Sass and Compass with ease. Let me know how you get on. Thanks.


  • 📂

    CSS… how to use sass and compass: Part One

    After listening to Chris Coyier speak about using Sass in CSS, I read up on it and decided to give it a bash myself. And… oh my god… it… is… frickin’ awesome!

    I love writing CSS anyway, so I wasn’t really thinking about anything to make it easier or quicker (which Sass does in spades). But what I didn’t expect was how much more creative it made me feel.

    So what are Sass and Compass?

    In short, Sass is a CSS pre-processor. It enables you to write much more condensed stylesheets and then have sass ‘turn them into’ real CSS. On top of this it gives you a lot of nifty little abilities to really help with your workflow and avoid repetition of code. Compass is a separate entity and sits on top of Sass to give even more goodies.

    I realize that to the uninitiated these terms may seem daunting – they did to me – but I can honestly say that once you get working with them you really will wonder how you did without them.

    Installing Sass and Compass (for windows)

    What follows is how I installed Sass and Compass on my windows machine. I’ve included the installation here, but if you run on anything different, or find something not working for you, then please visit the documentation pages (links at end of this post). The docs are fantastic and will have you up and running in no time!

    Firstly you’ll need to install Ruby. Don’t run away! This is all very easy, honest. Use one of the windows installers here, and that’ll be that.

    Once installed, open it up, type the following in and hit enter:

    gem install sass

    After a few seconds or so, Sass will be installed on your machine. Told you it was easy! Now you can leave it there and enjoy all of the fantastic benefits that Sass has to offer, or you can continue and install Compass in an equally simple way.

    Type each line separate, hitting enter after you do:

    gem update --system
    gem install compass

    And there you have it, Sass and Compass installed on your machine.

    Next if you go to the compass install docs here, it will guide you through setting up your first project with compass. The reason I urge you to do this at least once, is that it will create a file called ‘config.rb’, which you will use in each project. It is the file that dictates how your styles will be compiled.

    Starting to use them in your projects

    Again, I’d just like to point out that the following is how I use Sass and Compass in my own projects. There are ways of creating new projects in the command line, but I prefer to do it my own way. Mainly because, if I’m honest, the command line scares me.

    For most of my projects I kick off with the HTML5 Boilerplate. This is such a great resource for learning from if nothing more, but it’s also an awesome platform from which to start new projects. Get it here.

    Within the root directory of the Boilerplate folder, create a folder called ‘sass’ and paste the ‘config.rb’ file from the project created in the previous step. Within this config file you can edit certain properties to suit your needs. (I highly recommend setting the output style to ‘:compressed’, right before uploading to your live server)

    The settings in my config file are as follows:

    • http_path = “/”
    • css_dir = “css”
    • sass_dir = “sass”
    • images_dir = “img”
    • javascripts_dir = “js”
    • output_style = :expanded

    Lastly, to get us up and running, you need to create a file in the sass folder of your project. Let’s call it style.scss (please note the .scss extension). Then look inside your css folder of your project. If you have begun with the HTML5 Boilerplate, then there should already be a style.css file inside.

    At this point, I would highly recommend making a copy of the style.css file and saving it elsewhere, perhaps to your desktop temporarily. This will become apparent as to why in part two of this tutorial.

    Next, find and note down the location of your new project root (the one we are making with boilerplate, not the command line one). For Example, C:\xampp\htdocs\PROJECT_NAME (As I use xampp as my localhost). This may differ for you, but hopefully you should be able to work out your own. Then open up the ruby command prompt, type the following and hit enter:

    cd\

    This will set your path relative to your computer’s main hard drive. Then you simply tell compass to ‘watch’ your project for changes and to compile it into a css file:

    compass watch xampp\htdocs\PROJECT_NAME

    Obviously you would need to alter the path to match your own project location. If that has started correctly you should receive a message telling you that compass is ‘polling for changes’. What this means is that whatever changes are made to the sass file and saved, will be automatically converted into normal css.

    Now, opening the style.scss file in your code editor, write any css style you like as a quick test. Write it exactly as you would in a normal css file, then save it. Now open up the style.css file and you should see that same code copied from the sass style file.

    And that finishes off this introduction to sass and compass. I realize that the end result has given you nothing that is of use yet, but this was merely setting the stage for the awesomeness that is to come. In the next part I will show you how to further delve into the functionality of these great tools.

    Helpful Links

    Sass documentation | Compass Documentation