Reputation: 988
I have a Jekyll based blog that has some location data in the frontmatter of each post.
For example:
mapping:
locations:
- title: Times Square
latitude: 40.758885
longitude: -73.985134
- title: Central Park
latitude: 40.782841
longitude: -73.965350
I would like to retrieve all the locations in all of my posts so I can plot them on a map. Currently I display all locations on a map for a single post at the top of that post by passing the values into a javascript function I have modified from the plugin functionality here.
For example:
function () { jekyllMapping.loadScript( {{ page.mapping | jsonify }} ) };
I am having trouble retrieving all the locations from all the posts to pass to the same function as json.
I have tried:
{% capture travel_locations %}
{% for post in site.categories.travel %}
{% for location in post.mapping.locations %}
{{ location | jsonify }}{% unless forloop.last %},{% endunless %}{% endfor %}
{% unless forloop.last %},{% endunless %}{% endfor %}
{% endcapture %}
%Capture% appears to return as a string not an array element object so I'm forced to jsonify the output inside the loop. The final output is close but gives me no root json element and is not an array so I cannot iterate on it in the javascript. I can concatenate like this "{\"locations\":[" + {{ travel_locations }} + "]}"
but it of course just gets treated as a big escaped string and not a json object.
I've also tried splitting the capture result back into an array but still no luck.
{% assign my_locations = "{{ travel_locations | split:',' | jsonify }} %}
I hope I'm missing something really simple for retrieving variable values from all posts in a category?
Also, I host the blog as a static site on github pages so plugins are out of the question.
Upvotes: 1
Views: 48
Reputation: 52829
You can use assign
Create an empty array
{% assign locations = "" | split: "" %}
Then fill it with your locations
{% for post in site.categories.travel %}
{% for location in post.mapping.locations %}
{% assign locations = locations | push: location %}
{% endfor %}
{% endfor %}
You now have an array with all your locations, ready be jsonified.
Edit : This code will run on current Github pages' Jekyll version : 2.4.0
In order to work in sync with Github Pages' jekyll version, you need to create a Gemfile containing
source 'https://rubygems.org'
gem 'github-pages'
Then you do :
gem bundler install
bundle install
bundle exec jekyll serve
Bing ! http://0.0.0.0:4000/ is the place where everything is ok !
Upvotes: 2