How to get complex data from data folder in Hugo - hugo

Having the following file in the data folder:
# data/files.json
{
"test/file1.txt": "abcd/1234567890.txt",
"test/file2.txt": "bcde/1234567890.txt"
}
How do I obtain the value of "test/file1.txt" from the map? For example from this file
// layout/index.ace
= doctype html
html lang={{ .Site.Language.Lang }}
body
p {{ .Site.Data.files.????? }}
This is my environment:
$ go version
go version go1.9.2 linux/amd64
$ hugo version
Hugo Static Site Generator v0.35-DEV linux/amd64 BuildDate:

// layout/index.ace
= doctype html
html lang={{ .Site.Language.Lang }}
body
p {{ index .Site.Data.files "test/file1.txt" }}
does the trick.

Related

adding a page bundle with `hugo new`

I can add a new page with hugo new posts/new-page. But I want to add a page bundle. None of the following work
hugo new posts/2021/10/new-page creates a single new-page.md
hugo new posts/2021/10/new-page/ does the same as above
hugo new posts/2021/10/new-page/index.md works, kind. It creates index.md in the correct path and populates index.md with the archetypes/default.md except, it set the title to index instead of new page
so, how can I add a page bundle with hugo new
You can achieve that using Archetypes , quoting from the docs:
Since Hugo 0.49 you can use complete directories as archetype templates.
in the archetypes/ folder create a new folder named post-bundle/
inside it create a new file index.md
archetypes/post-bundle/index.md :
---
title: "{{ replace .Name "-" " " | title }}"
date: {{ .Date }}
draft: true
---
Then to create a page bundle:
hugo new --kind post-bundle posts/new-page
Notice: I don't think the approach you're doing to set the date in the url is correct , the above method will give a post with the following Permalink : example.com/posts/new-page you can then do the following to get the desired Permalink:
config.toml :
[permalinks]
posts = '/:year/:month/:title/'
In support of Mossab's answer...
a page bundle has three categories:
Branch,
headless
and leaf.
So if you made a file _index.md - it's a Branch bundle, off-the-bat. So viola that's how you make it with hugo new.
If you want a headless bundle, I believe you first need a leaf bundle, and then add:
headless = true to the front matter.
If you want a lead bundle you create an index.md file at any directory level.
So, I believe my point in this is, the way you do this is:
hugo new _index.md
Or
hugo new index.md
and if you want it headless, you use an archetype with the front matter (as Mossab desribes).
Please let me know if I'm possibly misunderstanding something.

Build a react project in django

I am embedding a react project inside my django app. I am serving the index.html file created by npm run build from django as opposed to just using django as a third party api. I like this approach as it leverages django user authentication/ csrf tokens/ etc.
After npm run build I am extracting the head and the scripts on index.html and putting them in my base.html of django, this way, the react scripts will be available wherever I need them and I can use my django templates for my navbar, footer etc.
The problem I am having is I have to copy and paste the headers and scripts on every build, so my question is if there is a way to make npm run build build the files with the same name every time, or perhaps another solution, so when I rebuild the react project I don't have to recopy and paste to base.html?
Here is a code snippet sample
base.html
<html>
<head>
<!-- Copy and pasted header files from react build-->
</head>
<body>
<navbar></navbar>
{% block content %}
{% endblock %}
<script> //copy and pasted scripts from react build - different script names on every build </script>
</body>
</html>
And then a file served by django
homepage.html
{% extend 'base.html' %}
<div class="other-django-stuff"></div>
{% block content %}
<div id="root"></div> // where my react project is anchored
{% endblock %}
Well, so what is needed in this case is a post build script that allows you to edit the file called base.html to have the right names and scripts produced by the build. I will describe here some conceptual steps on how to achieve this result.
Step n. 1: Change the package.json file to allow the execution of a script after the build
In this case I am using a JavaScript script file that will be run using nodejs, but you can use also other languages or shell scripts
"scripts": {
...
"build": "react-scripts build && node ./postbuild.js",
...
},
Note that, since the && operator is used, the postbuild.js file will executed only if the build will have success.
Step n. 2: Create the post build script that will write your base.html file
With the script you will be able to write the base.html file dynamically.
Note:
Since you can create the script in different languages, the script itself it is not included in the answer.
Thanks to Emanuele's guidance Here is the following solution using python. This assumes the react static build folder is added to STATIC_DIRS in settings.py:
base.html
<html>
<head>
{% include 'react_head.html' %}
</head>
<body>
<navbar></navbar>
{% block content %}
{% endblock %}
{% include 'react_scripts.html' %}
<script src='django-scripts.js'></script>
</body>
</html>
build_base.py
from bs4 import BeautifulSoup
index = open( "build/index.html" )
soup = BeautifulSoup( index, features="html.parser" )
links = soup.findAll( "link" )
scripts = soup.findAll( "script" )
with open( "./../templates/react_head.html", "w" ) as html:
html.write( r"{% load static %}" + "\n" )
for link in links:
url = link["href"]
if "favicon" in url: continue
fname = "/".join( url.split("/static/")[1:] )
link["href"] = '{% static ' + f"'{fname}' " + r"%}"
html.write( link.prettify() )
with open( "./../templates/react_scripts.html", "w" ) as html:
html.write( r"{% load static %}" + "\n" )
for script in scripts:
if 'src' in script:
url = script["src"]
fname = "/".join( url.split("/static/")[1:] )
script["src"] = '{% static ' + f"'{fname}' " + r"%}"
html.write( script.prettify() )
package.json
"scripts": {
...
"build": "react-scripts build && python ./build_base.py",
...
},

Where does imageConfig (HUGO) look for images when building the site?

I'm trying to get the size (width and height) of an image located inside my static folder
I wrote:
{{$imagelink := print "/static" (.Params.image | relURL) }}
{{$imgData := imageConfig $imagelink }}
<p>{{ $imgData.Height }}</p>
<p>{{ $imgData.Width }}</p>
where .Params.image is taken from the YAML metadata, e.g.: image: "images/my-image.PNG" of each post.
The previous works well if I save the file when the server is running. I can get the width and the height, but if I build my site with build_site(local = TRUE) (I'm using blogdown) HUGO can't find the images.
I tried debugging the error with {{ errorf "Specified file at %s not found." $imagelink }}, but whatever path I try it never founds the images.
I also followed this tutorial about imageConfig, where they point out the following:
but {{$imagelink := print "/static/static" (.Params.image | relURL) }} doesn't work either.
I haven't found official documentation regarding this issue. Any help is appreciated.
This issue was solved upgrading HUGO and blogdown to the latest version

how to fetch the frontmatter of any hugo markdown page (not just _index.md)

I'm trying to write a shortcode for my hugo site that fetches the title parameter of page.
I have a directory structure like this:
content
├── workshops
│   ├── foo
│   │   └── _index.md
│   ├── bar.md
This works perfectly:
{{ with .Site.GetPage "home" "workshops/foo"}}
{{ .Params.Title }}
{{ end }}
And this one consistently comes up blank (even though there is a title in the markdown).
{{ with .Site.GetPage "home" "workshops/bar"}}
{{ .Params.Title }}
{{ end }}
My question is: How so I get the title of a standalone page?
I've tried a bunch of different combinations of things and I'm just not coming right. I've tried reading the docs and they are horribly convoluted on this point.
I have a solution! I wrote a little Python3.7 script to make directories and move and rename markdown files and just ran it over my entire contents directory. This solved my problem but is a bit of a hack...
import logging
import os
from pathlib import Path
def fixup(path):
location = Path(path)
assert location.is_dir(), location
for child in location.iterdir():
if child.is_dir():
fixup(child)
else:
fix_file(child)
def fix_file(file_path):
name = file_path.name
if not name.endswith(".md"):
# we only care about markdown files.
return
check_metadata(file_path)
if name.startswith("_index."):
# looks good
return
# make a directory with the same name as the file (without the extension)
suffix = ''.join(file_path.suffixes)
prefix = name[: -len(suffix)]
new_dir = file_path.parent / prefix
new_dir.mkdir()
new_path = new_dir / f"_index{suffix}"
file_path.rename(new_path)
def check_metadata(file_path):
""" given the path to a markdown file, make sure that the frontmatter includes
the required metadata
"""
# TODO
# required = ['title']
# allowed = ['pre', 'weight', 'ready']
if __name__ == '__main__':
fixup('content')
Two differences:
Use the global site variable
Just pass the page name as the argument
{{ with site.GetPage "workshops/bar" }}
{{ .Title }}
{{ end }}

How to add a new hugo static page?

From the "getting started" section it seems this should work, but it doesn't.
hugo new site my-site
hugo new privacy.md
hugo server --watch --includeDrafts
curl -L localhost:1313/privacy/index.html
# 404 page not found
curl -L localhost:1313/privacy.html
# 404 page not found
curl -L localhost:1313/privacy/
# 404 page not found
How can I add a new page?
This is the best tutorial how to create static "landing pages" on Hugo: https://discuss.gohugo.io/t/creating-static-content-that-uses-partials/265/19?u=royston
Basically, you create .md in /content/ with type: "page" in front matter, then create custom layout for it, for example layout: "simple-static" in front matter, then create the layout template in themes/<name>/layouts/page/, for example, simple-static.html. Then, use all partials as usual, and call content from original .md file using {{ .Content }}.
All my static (landing) pages are using this method.
By the way, I'm not using hugo new, I just clone .md file or copy a template into /content/ and open it using my iA Writer text editor. But I'm not using Hugo server either, adapted npm-build-boilerplate is running the server and builds.
Just tested OK with this on Hugo 0.13:
hugo new site my-site
cd my-site
hugo new privacy.md
hugo server -w -D
curl -L localhost:1313/privacy/
Note: You have to either use a theme or provide your own layout template to get something more than a blank page. And of course, some Markdown in privacy.md would also make it even nicer.
See http://gohugo.io/overview/introduction for up-to-date documentation.
I had a similar requirement, to add static page (aboutus in this case). Following steps did the trick,
Created an empty file content/aboutus/_index.md
Created aboutus.html page layouts/section/aboutus.html
Make you have some default frontmatter set in archetypes/default.md
# archetypes/default.md
+++
title: "{{ replace .Name "-" " " | title }}"
date: {{ .Date }}
draft: true
+++
And the single layout in layouts/_default/single.html to render some variable or content
# tags to render markdown content
<h1>{{ .Title }}</h1>
<p>{{ .Content }}</p>
<span>{{ .Params.date }}</span>
Now type hugo new privacy.md which will create a new page on the following directory in content/privacy.md
Take "About" as example:
# will create content/about.md
hugo new about.md
Edit about.md and add the last 2 lines, the metadata/front matter looks like:
title: "About"
date: 2019-03-26
menu: "main"
weight: 50
That should work.

Resources