None of the plugins referenced in other answers worked.
So here's my plugin in 20 lines that did work for me:
class RootInclude < Liquid::Tag
def initialize(_tag_name, markup, _parse_context)
super
@markup = markup.strip
end
def render(context)
expanded_path = Liquid::Template.parse(@markup).render(context)
root_path = File.expand_path(context.registers[:site].config['source'])
final_path = File.join(root_path, expanded_path)
read_file(final_path, context)
end
def read_file(path, context)
file_read_opts = context.registers[:site].file_read_opts
File.read(path, **file_read_opts)
end
end
Liquid::Template.register_tag('root_include', RootInclude)
Create a folder called _plugins
in the root of your project if you don't already have one. Then place a file there with this content. Then restart Jekyll.
Now in your pages, layouts and includes you can do this:
{%- root_include assets/blocks/code-sample.html -%}
or this:
{%- root_include /assets/blocks/code-sample.html -%}
or this:
{%- root_include ./assets/blocks/code-sample.html -%}
They're all the same.
If you have a post with front matter like this:
title: "My Post"
code: /assets/blocks/code-sample.html
---
You can then do this:
{%- root_include {{ page.code }} -%}
If you have a post with front matter like this:
title: "My Post"
code: code-sample.html
---
You can then do this:
{%- root_include /assets/blocks/{{ page.code }} -%}
After 7 years I find it's a bit mindboggling that such a basic use-case is still unsupported by Jekyll. I wanted exactly the same as Brad. I wanted to have a code-snippet in a single place, that I could both include
and make available through an iframe
. For whoever is interested, this is a simplified version of what I'm using:
{%- assign block_path = page.block.path | prepend: '/assets/blocks/' -%}
<div class="block-embed">
<iframe src="{{ block_path }}" sandbox="allow-scripts allow-forms" marginwidth="0" marginheight="0" scrolling="no"></iframe>
<a href="{{ block_path }}" target="_blank" class="open-new-tab-link">{%- include icons/new-tab.svg -%}</a>
</div>
<div class="block-source">
{% highlight html linenos %}
{%- root_include {{ block_path }} -%}
{% endhighlight %}
</div>
Very odd that we would need a custom plugin for this.
_
means that Jekyll won't include that directory in_site
when it compiles. For my use case, I need to include/patterns
in/_site
because I'm referencing those files in an iframe. – Ethelyn