Hi guys!
I want to start my blog, and I want to use as cool stuff as hugo to do it, even though I’m not that much experienced in programming / golang and so on.
Here’s my issue:
When someone enters my page, there should be a div with a particular (eg the most recent) post I wrote in it.
I read the docs at gohugo.io, but I didn’t figure out how to do it unfortunately.
I tried to somehow access a post eg content/hi.md from my layouts/index.html. Is this possible?
you’ve have to filter the page you want to display on the homepage. Normally the homepage lists the latest blog posts. You use range to list the posts and first to define a limit of posts.
The snippet below should display the latest post:
{{ range first 1 .Data.Pages }}
<h1>{{ .Title }}</h1>
<p>{{ .Summary }}</p>
<!-- ...or if you want to display the whole text... -->
<p>{{ .Content }}</p>
{{ end }}
Hey @digitalcraftsman,
thanks for your answer! That helped me a lot and led me to new thoughts!
I wanna go a bit further.
Can you tell me where to start reading about what .Data.Pages is?
Is it a variable with all the rendered content of the content/ folder in it?
I want to display now not the latest, but one particular post. Can I somehow do an if condition instead of a range? Maybe with accessing the .Params thing, can I access this at layouts/index.html somehow?
It’s a list of all pages. A page is simply an object with attributes like the title, the content, a summary etc. You can find the whole list of attributes here. Inside the loop your context a.k.a. the . is a page object. Therefore, you can directly access the title with .Title for example.
Is it a variable with all the rendered content of the content/ folder in it?
This is correct for the homepage.
By using if you could filter the content as follows:
{{ range .Data.Pages }}
{{ if eq .Title "Some title" }}
{{ .Content }}
{{ end }}
{{ end }}
But there is a shorter way for such filters with the where function.
{{ range first 1 (where .Data.Pages "Params.foo" "something") }}
{{ .Content }}
{{ end }}
First of all we filter all pages with where. .Params allows you to access the frontmatter. Here it checks if the variable foo equals something. If this is the case then it will be added to a list that where returns at the end.
Because we only want to have the first item of that list we apply first 1 to it.