Skip to main content
  1. Note/

Hugo Functions: Get Slice From Specific Range

·2 mins· ·
Blog En Hugo
Liu Zhe You
Author
Liu Zhe You
Skilled in full-stack development and DevOps, currently focusing on Backend.
Table of Contents

About Hugo
#

Hugo is my current static site generator.

  • Hugo is much faster than other static site generators like Jekyll, Hexo, etc.
  • Supports partials and shortcodes for template functions.
  • Supports functions for manipulating data in templates.

Common Hugo shortcodes example:

/layouts/shortcodes/myImage.html

{{ $image := .Get "image" }}

<img class="w-100" src="{{ $image }}" alt="image">

And you can use it in your markdown file like this:

{{< myImage image="https://example.com/image.jpg" >}}

Current Hugo Theme: Blowfish
#

I’m using the blowfish as my current Hugo theme! It provides the codeimporter shortcode for importing code snippets from a URL.

{{< codeimporter url="https://raw.githubusercontent.com/username/repo/branch/file.go" type="go" >}}

However, it doesn’t support getting files from a specific range.

Solution for Getting a Slice from a Specific Range in Hugo
#

Since Hugo doesn’t support substr or cut functions for slicing a slice from a specific range, we can utilize the concept of using the head and tail GNU commands to grep start to end lines of files on Linux.

For Linux: Using head and tail to specify the range of lines to be displayed.

head -n 10 file.txt | tail -n 5
# display line 6 to 10

For Hugo: We can use the first and after functions in Hugo to get a slice from a specific range.

The first and after functions are in the collection functions category.

{{ $lines := slice "line1" "line2" "line3" "line4" "line5" }}
{{ $startLine := 2 }}
{{ $endLine := 4 }}

{{ $startLine := sub $startLine 1 }}
{{ $selectedLines := first $endLine $lines }}
{{ $selectedLines := after $startLine $selectedLines }}

PR for Blowfish Theme: Add startLine and endLine Support for codeimporter
#

I’ve created a PR for the blowfish theme to add startLine and endLine support for the codeimporter shortcode.

PR: https://github.com/nunocoracao/blowfish/pull/1558

codeimpoter-pr

Reference
#

Related

Redis Persistence: RDB and AOF
·5 mins
Blog En Database Redis
Detailed explanation of Redis persistence settings: RDB and AOF. Pros and cons of RDB and AOF. Detailed implementation with Redis source code.
How to use Transaction in SqlAlchemy
·2 mins
Blog En SqlAlchemy Backend Python
How to transaction in SqlAlchemy
Python: Read File(BinaryIO) Multiple Time
·1 min
Blog En Python
Read file (BinaryIO) multiple time in Python. Solution to prevent empty content in the second read.
PgBouncer: Lightweight Postgres Connection Pool
·2 mins
Blog Database En Postgresql
Solving Django backend DB connection overload with PgBouncer
Cloudflare Tunnel
·3 mins
Blog En
Setup Cloudflare Tunnel for NAT, an alternative to Ngrok
Tmux Cheat Sheet
·3 mins
Blog En
Common tmux commands Cheat Sheet