Last active
May 10, 2020 06:31
-
-
Save jaredcwhite/dc11dc578563923befebb0804c290040 to your computer and use it in GitHub Desktop.
Add Javascript Front Matter to a layout template in Bridgetown 😊 https://www.bridgetownrb.com
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Add node-runner to your site's Gemfile | |
# Then place this file in your plugins folder… | |
require "node-runner" | |
class JSFrontMatter | |
def initialize | |
Bridgetown::Hooks.register :site, :pre_render do |site, payload| | |
docs = (site.documents + site.pages).map{|doc| doc.to_liquid.to_h} | |
site.layouts.each_value do |layout| | |
self.search_data_for_javascript_code(layout, site, docs) | |
end | |
end | |
end | |
def search_data_for_javascript_code(layout, site, docs) | |
data_keys = layout.data.keys | |
data_keys.each do |k| | |
next unless k.end_with? "_javascript" | |
v = "function main(config, documents) {\n" + layout.data[k] + "\n}" | |
runner = NodeRunner.new(v) | |
layout.data[k.sub("_javascript", "")] = runner.main(site.config, docs) | |
end | |
end | |
end | |
JSFrontMatter.new |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
layout: default | |
awesome_javascript: | | |
const camelcase = require("camelcase") | |
const firstTitle = documents[0].title | |
return `${"Wow".toUpperCase()}, this is cool! 😃 ${camelcase(firstTitle)} ~ Source Dir: ${config.source}` | |
--- | |
<h1>{{ page.title }}</h1> | |
{{ content }} | |
JS: {{ layout.awesome }} | |
<!-- outputs: WOW, this is cool! 😃 groovyBlogPost ~ Source Dir: /path/to/site/src --> |
One last bit of zaniness…you could put a JS file in your plugins
folder and then require that from the front matter…
// plugins/freaky.js
module.exports = function(config) {
return `OK, now this is getting ${config.permalink} freaky!!`
}
---
freaky_javascript: |
const freaky = require(process.cwd() + "/plugins/freaky")
return freaky(config)
{{ layout.freaky }}
output: OK, now this is getting pretty freaky!!
🤯
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
After getting inspired by Javascript Front Matter over in the world of Eleventy, Gatsby, etc. I worked on Ruby Front Matter for Bridgetown…and then I started wondering why we can't ALSO have Javascript Front Matter? 🤔🤓