amakelov amakelov - 3 months ago 15x
Javascript Question

Use liquid 'include' tag from javascript

I'm trying to implement search for my jekyll-based website, and I followed this implementation. Everything works as it should, however, when I return the search results, I want to use the template I have for post previews on my front page, which is stored in the _includes/ folder of my jekyll setup. In liquid, it would go something like

{% for post in search_results %}
{% include post-preview.html %}
{% endfor %}

However, the search results html string is constructed in javascript, where I gather you can't use liquid tags. Is there any easy way around that?


I've found a somewhat hackish way to do it since I asked the question, so I'll put it up here in case anybody needs it.

So, to load the template file, I used ajax:

  var xhReq = new XMLHttpRequest();"GET", 'post-preview.html', false);
  var template = xhReq.responseText;

Now, after this, the variable template holds the contents of the text file post-preview.html, which looks something like this:

<div class="post-preview">
  <div class="post-title">
    <div class="post-name">
      <a href="{{ post.url }}">{{ post.title }}</a>
    <div class="post-date">
      {% include time.html %}

  <div class="post-snippet">
    {% if post.content contains '
    <!--break-->' %} {{ post.content | split:'
    <!--break-->' | first }}
    <div class="post-readmore">
      <a href="{{ post.url }}">read more-></a>
    {% endif %}
  {% include post-meta.html %}

Now our job is to replace the liquid calls to things like post.url with javascript. This is easy for post.url and post.title which we can handle with the .replace method for strings in javascript. However, it's more complicated for code such as the one that splits the post contents so that only a snippet can be shown in the preview.

So, to me at least, it seems that we need to write javascript code that does the same thing. Since the whole purpose of this exercise was not to have to keep the same html code in two places (the post-preview.html file and the search.js file), it seems that we need some automatic way to remove the liquid code and inject javascript. I have asked a question to (some of) this effect here.