Montag, 17. Februar 2014

Posting Code Blocks on a WordPress Site




CSS-Tricks





Posting Code Blocks on a WordPress Site



So you've installed WordPress and want to blog about code. Yay! You're a hero and I thank on behalf of myself an coders everywhere. Here's what you'll need to do and think about to actually get publishing blocks of code.



The HTML for a "code block"


There is an element specifically for code: <code>. I'd say it's semantically correct to wrap any and all code in it. Browser's default stylesheets leave it as inline element, and I'd recommend you leave it that way so you can use it within sentences like I did in the last sentence.


But you'll want to use a block-level element to wrap a block of code. <pre> is the perfect element for that, as it naturally retains spacing. "Pre" as in "Preformatted text". Multiple spaces will render as multiple spaces instead of collapsing into a single space as normally happens in HTML. That's perfect for code, because you'll likely want to use indentation in a block of code and you don't want to resort to any &nbsp; shenanigans.


So:


<pre><code>Your 

block

of

code

here.</​code></​pre>

Turn off the "Visual" editor


By default, WordPress lets you switch between Visual and Text tabs in the editor.



For you, the Visual editor has to go. You will never use it. You want full control of the text you are writing and want it to stay just how you write it when you save it.


Turn it off under Users > Your Profile



Are you going to blog in Markdown or not?


Here on CSS-Tricks I do not, but if I could go back in time to the beginning I probably would. On most subsequent blogs I've done, I do use Markdown and prefer it. To post a block of code in Markdown, you'll need to indent that code four spaces on every single like, like this:


Yadda yadda yadda. I'm a *paragraph* in Markdown. Here's a [link to Google](http://google.com). Here's a block of code:

<div>
<p>I'm some code.</p>
<div>

Another paragraph here.

Manually doing that is going to get old very fast. So you'll want to replace your editor buttons with Markdown buttons. It looks like the plugin Markdown Quicktags can do that.



What's cool about using Markdown is that you don't have to worry about escaping the code. So those angle-brackets are no rendering threat, Markdown will escape them for you. In other words, all those angle brackets (<) in the HTML example above will be turned into &lt; and thus display on the screen as an angle-bracket, not attempt to be rendered by the browser.


That Markdown example above will be turned into this before it hits the browser:


<p>Yadda yadda yadda. I'm a <em>paragraph</em> in Markdown. Here's a <a href="http://google.com">link to Google</a>. Here's a block of code:</p>

<pre><code>&lt;div&gt;
&lt;p&gt;I'm some code.&lt;/p&gt;
&lt;div&gt;

<p>Another paragraph here.</p>

If you're interested in blogging in Markdown, you have some options. Jetpack, the Automattic-created and maintained plugin, now offers it as part of it's mega-pack of offerings. At the time being I use WP-Markdown here on CSS-Tricks (I know I said I don't use Markdown, but I do for the Forums and comments, just not blogging).


Two I haven't personally tried are Typewriter and Markdown on Saved Improved.


There is a fairly major limitation here though. Notice that the four-spacing indentation converts into a <pre><code> block, but there was no opportunity there to add attributes to those tags. Attributes (like classes and data-* attributes) are a common need. You might want to use a syntax highlighter (we'll talk about those later) that requires some attributes to do it's thing. Or you might want to identify the code block somehow by language.


GitHub is a big user of Markdown, and they solved this issue by adding the triple-backtick style of code blocks, like this:


```
<div>
<p>I'm some code.</p>
<div>
```

I'd call this straight up better. It's easier to jump into a code block while writing without having to worry about the indentation thing. Plus code has it's own indentation going on so it's nice to start flush-left with that.


Beyond that, GitHub-flavored Markdown allows you to specify the language right in the Markdown syntax. So our example could be:


```html
<div>
<p>I'm some code.</p>
<div>
```

Which gives:


<div class="highlight highlight-html">
<pre>
<span class="nt">&lt;div&gt;</span>
hi
<span class="nt">&lt;/div&gt;</span>
</pre>
</div>

I'm not sure why it skips the <code> tag and it looks like it does the syntax highlighting server-side with those spans. Just be aware of all that I suppose.


I was able to find wp-gfm which is a GitHub-flavored Markdown plugin for WordPress.


If you go no-Markdown, you'll need to escape the code.


CSS rarely needs escaping, but HTML for sure does, and JavaScript sometimes has HTML in it as well as just about all backend languages, so you might as well just assume you need to escape all code.


You could do it manually by converting all <'s into &lt;'s, but you'll go nutty doing that. You could use a tool like Postable to copy-and-paste blocks to be escaped, but that's slow and tedious too.


I prefer using a plugin called Code Markup for this. It just auto-escaped anything it finds within <code> tags so you just never have to think about it.


Because I use that plugin on this site, I can do stuff like:


<pre data-lang="HTML"><code class="language-markup"><div>
<p>I'm some code.</p>
<div></​code></​pre>

And it works great. No escaping. Full attribute control.


Handling Syntax Highlighting


Remember that one option for syntax highlighting blocks of code is not syntax highlighting. Certainly that would be the fastest and easiest way. But you might want it. Personally I like it. I like the way it looks. Here's a few options.


What essentially happens with any syntax highlighter is bits of code end up getting wrapped in <span>s with class names that you colorize with CSS. Choosing is a matter of features.


Prism.js


Here on CSS-Tricks, I use (and recommend) Prism by Lea Verou as it works with those right out of the box. It's small, fast, and (my favorite) as rational class names for styling. You choose which languages you want it to support as you download it.


I also use that escaping plugin, meaning I don't need to escape HTML inside code tags, so again that looks like this:


<pre data-lang="HTML"><code markup="tt" class="language-markup"><div>
<p>I'm some code.</p>
<div></​code></​pre>

That class="language-markup" on the code tag is what Prism picks up on to syntax highlight. It works automatically on all code it finds with that class name pattern by default, but you can use the API instead if you want to do your own thing.


The data-lang attribute on the <pre> tag isn't required, but I might use that in CSS to style the look (and label) the code as HTML. The markup attribute you see in there relates to the escaping plugin. By default it still renders things like <span> and <a> elements, but if you use that attribute with an element-as-value that you don't really plan to use, it will escape those too.


Prettify


An extremely popular one is google-code-prettify. To syntax highlight a block, you put class="prettyprint" on either the code or pre tag.


It's a larger file size than Prism, but one advantage is that it auto-detects language (and supports a ton of languages), so it should work on just about anything without you having to specify it.


Others


Digging around a little, there are plenty more that I can't vouch for but seem like they'll do the trick: Rainbow, SyntaxHighlighter, Chili (jQuery), JSHighlighter, jQuery.Syntax (jQuery), GeSHi, Lighter (MooTools), highlight.js, SHJS, and Pygments (Python).


Deciding


To decide amongst these, you might think about these things:



  • What languages do I mostly need to support?

  • Do I want to show line numbers?

  • Do I need to put links within the code?

  • Do I want to be able to highlight parts of the code or lines?

  • Do I have legacy code blocks I need to support? What format are they in?

  • Is the code easy to copy and paste? Do I want features to help with that?

  • Is client-side syntax highlighting OK or do I want it to happen server-side?


Dealing with Legacy Code


If you have a bunch of code blocks on a site already, I'd still recommend choosing a syntax highlighter that you like the features of for current and future use. Then finding a way to make it work for the older blocks.


For instance, let's say I have a legacy code block that is marked up like this:


<pre><code class="javascript">
var thing = document.getElementById("thing");
</​code></​pre>

That's not the right class name for Prism. So I might use jQuery to do something like:


$("code.javascript")
.removeClass("javascript")
.addClass("language-javascript");

And make sure that JavaScript runs before Prism does. I might also take the opportunity to $.trim() the code because, as written above, there is an extra return at the top and bottom which might affect the styling of the code block.


I mean this just as an example. The overall point is: you can manipulate the legacy code blocks as needed to fit the new format.


Third Party Help


When creating the Embedded Pens feature on CodePen, we knew that displaying demos and code in blog posts is kind of a pain in the butt, so we set out to make that easier.


Here's an example of some CSS (complete with a demo) that I'm embedding into this post:



* {
@include box-sizing(border-box);
}

section {
background: #eee;
max-width: 600px;
margin: 0 auto;
padding: 20px;
overflow: hidden;
}

.module {
width: 48%;
min-height: 200px;
background: white;
position: relative;
float: left;
padding: 20px;
margin-right: 4%;
margin-bottom: 4%;
&amp;:nth-child(even) {
margin-right: 0;
}
box-shadow: 0 1px 3px rgba(black, 0.2);
}

body {
background: url(http://s.cdpn.io/3/blurry-blue.jpg);
background-size: cover;
padding: 30px;
}

.come-in {
transform: translateY(150px);
animation: come-in 0.8s ease forwards;
}
.come-in:nth-child(odd) {
animation-duration: 0.6s;
}
.already-visible {
transform: translateY(0);
animation: none;
}

@keyframes come-in {
to { transform: translateY(0); }
}

See the Pen Slide in from bottom boxes by Chris Coyier (@chriscoyier) on CodePen.



I don't need to worry about syntax highlighting, escaping, or anything, and get the benefit of showing the rendered demo as well. Plus, if you choose, we embed the code of your choice right in there so in the case JavaScript doesn't run (e.g. an RSS reader) the code will still be present in semantic tags.


Many of the other code editor sites offer embedded code as well like JSFiddle and JSBin. GitHub Gists can be useful for this too. Perhaps my favorite reason for using third-party tools for this is that you can go update the demo there and the blog post automatically has the new code. You don't have to update stuff in two places. Although I often just plop code directly into posts as well.




Do you have your own way of handling code blocks on a WordPress site? Do share.





Posting Code Blocks on a WordPress Site is a post from CSS-Tricks








Keine Kommentare:

Kommentar veröffentlichen