My Profile Photo

Rich Werden

Web Developer & Software Engineer


A site for Rich to write about code and show some completed projects for future reference...


Including JS In Jekyll Markdown

I don’t know if calling the markdown language for jekyll ‘Jekyll Markdown’ is the best nomenclature. I mean, it is to me at its heart really markdown, but then I’ve got the liquid templating language. :aside: templates within non-templated material. oy.:

So I was thinking about how to include some dynamically-rendered content in one of these pages. But then, yaknow, the whole point of this system is to pre-compile everything. Was trying to think of a way to inject javascript into my jekyll markdown. Then I remembered the _includes folder. So, here’s what I came up with

Method 1: Inline <script> Tags

A Quick & Dirty Not-The-Best-Idea

Since you can use whatever HTML tags you want inline in a Markdown post, if I were to arbitrarily put a <script> tag to start code and end it with a </script> in the middle of my writing, it would actually take effect. If you don’t believe me, go ahead and take a look at your console, and then the source for this page. (I’ll wait)…

While this may be useful, it does seem a little hack-y and it would be tough figuring out where code went awry, so I gotta say, I’d recommend the following idea of using jekyll’s ‘includes’ over inlining your JS.

Method 2: The _includes Folder

(aka “The Clean Way”)

Then I remembered the _includes folder. You can bring in anything to the middle of a page by using the liquid\ruby\whatever percentage syntax: {% include some-other-file.html %}. There is some great advanced and dynamic usage of includes over at idratherbewriting.com

Since the _includes folder import process is looking for complete .html files, what ya could do is write a super-vanilla HTML markup, and then write whatever code you want inside of a <script> tag. So I’d write the following and save it as something.html inside the site’s _includes directory

<!DOCTYPE html>
<html>
  <head>
    <title></title>
  </head>
  <body>
    <script>
      /*** Put JS Content Here... ***/
    </script>
  </body>
</html>

Then, by typing {% include something.html %} the file will be imported\injected into this post and the javascript code should be coming along for the ride…

Method 3: Outside Forces

Let me add that apparently you can pull in a live file from a github repo by using that file’s raw incarnation (available via the rawgit website). Haven’t tried it yet…