Blogdown – shortcode for radix-like Bibtex

In the spirit of trying out new things in Hugo since my last post on modifying the RSS feed for this website, I attempted to implement the new citation feature from the new radix package by RStudio.

Essentially, I tried using a custom hugo shortcode to replicate the text and BibTex citation at the bottom of the page when rendered by radix.

Custom shortcodes should live in the layouts/shortcodes directory as a example_shortcode.html and then the HTML code can be injected into the page through a shortcode as ``

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Citation:
For attribution, please cite this work as


{{$.Page.Params.author}}. ({{dateFormat "2006-01-02" $.Page.Params.date }}). "{{$.Page.Params.title}}". Retrieved from {{ $.Page.Permalink }}. 


BibTex citation

 @misc{{{$name_string := replace $.Page.Params.author " " "_"}}{{$name_string}}{{dateFormat "2006-01-02" $.Page.Params.date }},


 title = {{$title_str := $.Page.Params.title}}{{printf "{%s}" $title_str}},


 howpublished = {{$url_str := $.Page.Permalink}}{{printf "{\url{%s}}" $url_str}},


 year = {{$year_str := dateFormat "2006" $.Page.Params.date }}{{printf "{%s}" $year_str}}

 }


The first two lines of the shortcode are simple HTML tags, and the next line {{$.Page.Params.author}}. ({{dateFormat "2006-01-02" $.Page.Params.date }}). "{{$.Page.Params.title}}". Retrieved from {{ $.Page.Permalink }}. takes in the parameter values from the blog post. So author, the date, and the post title.

Date can be formatted by specifying the format using dateFormat.

The main difficulty came with getting the BibTex citation to show up properly. First, BibTex works best with curly brackets, but double curly brackets are used to access and run Hugo code and functions. I could not find any way of escaping the curly bracket used in BibTex formatting. {{{ in a row would throw errors so I first used printf to insert the string between the curly brackets.

In this line of code, {{$title_str := $.Page.Params.title}}{{printf "{%s}" $title_str}}, I first assigned the parameter to a string variable and then printed the string with printf. But this method did not work for the first and last curly brace. The simpler soluation is to just use HTML special characters which I only realized after examining the hugo documentation site page source.

So really, the shortcode could be cleaner if I just used HTML special characters instead of a prinf string insert, but I am unfamiliar with the HTML codes that the go code is more understandable to me than trying to figure out what each HTML character actually is.

And here is the end result.

Citation:

For attribution, please cite this work as

``

BibTex citation

``

I haven’t looked up what is the difference between a partial and a shortcode in hugo but I imagine it would not be hard to add this as a partial and have an automatic citation set up for every blog post/page.

Related