Hugo Flashcard Shortcode
Cool! How do I get it for my Hugo site?
Download these three files:
And put them in the right places in your Hugo project. The JS and CSS files
go in your static/js/flashcard.js
and static/css/flashcard.css
respectively.
The shortcode HTML file goes to layouts/shortcodes/flashcard.html
(you can
also put it in the theme’s shortcodes folder if you want to use it in multiple
sites).
Here’s how you use it:
{ { < flashcard question="question" > } }
answer
{ { < /flashcard > } }
Just delete the spaces between the {
-s. They are here to avoid rendering the
shortcode.
Why did I build this?
All right, so here’s the deal. Recently I’ve started prepping for job interviews since I’m leaving my current job. So I’m reading some books actively by summarizing points from the books in flashcards to help me remember them.
I’ve been using logseq’s flashcards to learn and it’s been super engaging.
But! I can’t share the flashcards with
y’all from logseq
. So, I decided to take a short diversion and build a
flashcard shortcode for Hugo.
RTFM and plan
I’ve avoided my instinct to jump to the code, and instead I’ve read the docs for Hugo’s shortcodes first and the “Create Your Own Shortcodes” article as well.
After reading this, here’s the plan. The flashcard has two parts: The question and the answer. The card should show the question, and when the user clicks on it, reveal the answer. I’d like to do it with a cool animation in CSS since recently I’ve been dabbling in CSS.
The question will be a named parameter to the shortcode, and the answer
will be the inner content of the shortcode. So something like this, just
without the spaces between the {
-s. They are here to avoid rendering 😅
{ { < flashcard question="What is the answer to life, the universe and everything?" > } }
42! _some markdown_ [things such as links](/posts)
{ { < /flashcard > } }
A play-by-play
HTML: Create a shortcode file
This is the first version of the shortcode file:
{{ with .Get "question" }}
<div class="flashcard">
<div class="flashcard__front">{{ .Get "question" }}</div>
<div class="flashcard__back">{{ .Inner | markdownify }}</div>
</div>
{{ else }} {{ errorf "missing value for param 'question': %s" .Position }} {{
end }}
Aaaaand:
failed to render shortcode "flashcard":
failed to process shortcode:
execute of template failed: template: shortcodes/flashcard.html:6:35:
executing "shortcodes/flashcard.html" at <.Get>:
can't evaluate field Get in type string
Huh. Reading it closely, seems like the with
template directive changes the
context of the parameter when you render the template. From Go’s documentation:
{{with pipeline}} T1 {{else}} T0 {{end}}
If the value of the pipeline is empty, dot is unaffected and T0 is executed; otherwise, dot is set to the value of the pipeline and T1 is executed.
Fixed the code to:
<div class="flashcard">
<!-- This "with" is for error handling, see
https://gohugo.io/templates/shortcode-templates/#error-handling-in-shortcodes
-->
{{ with .Get "question" }}
<div class="flashcard__front">{{ . }}</div>
{{ else }} {{ errorf "missing value for param 'question': %s" .Position }} {{
end }}
<div class="flashcard__back">{{ .Inner | markdownify }}</div>
</div>
This is the a screenshot of output before any CSS was applied:
CSS: Style it 💅
I’ve added some CSS to make it look like a flashcard. Writing it was kinda fun, based on my experience with CSS Battles.
The final CSS includes support for the next steps as well.
JS: Reveal the answer on click
Spoiler alert: This code doesn’t work, we discover the problem in the QA section.
With the JS implemented, you can click on the question and see the answer. I’ve added some janky JS code to make it work and I had to retrofit the HTML as well.
The interesting part in the HTML is using the SHA hash of the question as the
id
of the answer. This way, I can use the id
to find the answer in the DOM.
This is a super useful template function that Hugo provides, here is the
docs. I f**king love Hugo!
Question:
<button class="flashcard__front" onclick="toggleAnswer({{ . | sha1 }})" role="button">{{ . | markdownify }}</button>
Answer:
<div id="{{ .Get "question" | sha1 }}" class="flashcard__back">{{ .Inner | markdownify }}</div>
JS couldn’t be simpler. Toggle the class based on the ID:
function toggleAnswer(id) {
var answerElement = document.getElementById(id);
if (answerElement.classList.contains('unblur')) {
answerElement.classList.remove('unblur');
} else {
answerElement.classList.add('unblur');
}
}
Let’s do some QA
I’ve added some tests to make sure the shortcode works as expected.
Two flashcards with the same question
This discovered a bug! Instead of opening both flashcards, only the first one
was opened. According to HTML spec,
the id
attribute SHOULD be unique. I added some code to make the id
unique,
which made the HTML slightly more complex:
<!-- get a random string to add to each ID -->
{{ $seed := now.Format ":time_full" }} {{ $random := delimit (shuffle (split
(md5 $seed) "" )) "" }}
<!-- create a unique ID for the answer, based on the question's SHA and the
random string. -->
{{ $questionSHA := . | sha1 }} {{ $answerID := printf "answer-id-%s-%s"
$questionSHA $random }}
<!-- The flashcard itself -->
<div class="flashcard">
<div class="notepad-line"></div>
<button
class="flashcard__front"
onclick="toggleAnswer({{ $answerID }})"
role="button"
>
{{ . | markdownify }}
</button>
<div id="{{ $answerID }}" class="flashcard__back">
{{ $.Inner | markdownify }}
</div>
</div>
Here’s how the different IDs look in the DOM now (you can also check it with your own dev tools):
Markdown in the question
✅
Richer content
✅
According to The Hitchhiker’s Guide to the Galaxy:
“You’re really not going to like it,” observed Deep Thought.
“Tell us!”
“All right,” said Deep Thought. “The Answer to the Great Question…”
“Yes..!”
“Of Life, the Universe and Everything…” said Deep Thought.
“Yes…!”
“Is…” said Deep Thought, and paused.
“Yes…!”
“Is…”
“Yes…!!!…?”
“Forty-two,” said Deep Thought, with infinite majesty and calm.”
Let’s test with the entire markdown test file as the answer, just for completeness:
✅
Markdown: Syntax
- Cool! How do I get it for my Hugo site?
- Why did I build this?
- RTFM and plan
- A play-by-play
- Overview
- Block Elements
- Span Elements
- Summary
- Keep this open to copy the snippet, if you want
Note: This document is itself written using Markdown; you can see the source for it by adding ‘.text’ to the URL.
Overview
Philosophy
Markdown is intended to be as easy-to-read and easy-to-write as is feasible.
Readability, however, is emphasized above all else. A Markdown-formatted document should be publishable as-is, as plain text, without looking like it’s been marked up with tags or formatting instructions. While Markdown’s syntax has been influenced by several existing text-to-HTML filters – including Setext, atx, Textile, reStructuredText, Grutatext, and EtText – the single biggest source of inspiration for Markdown’s syntax is the format of plain text email.
Block Elements
Paragraphs and Line Breaks
A paragraph is simply one or more consecutive lines of text, separated by one or more blank lines. (A blank line is any line that looks like a blank line – a line containing nothing but spaces or tabs is considered blank.) Normal paragraphs should not be indented with spaces or tabs.
The implication of the “one or more consecutive lines of text” rule is
that Markdown supports “hard-wrapped” text paragraphs. This differs
significantly from most other text-to-HTML formatters (including Movable
Type’s “Convert Line Breaks” option) which translate every line break
character in a paragraph into a <br />
tag.
When you do want to insert a <br />
break tag using Markdown, you
end a line with two or more spaces, then type return.
Headers
Markdown supports two styles of headers, [Setext] [1] and [atx] [2].
Optionally, you may “close” atx-style headers. This is purely cosmetic – you can use this if you think it looks better. The closing hashes don’t even need to match the number of hashes used to open the header. (The number of opening hashes determines the header level.)
Blockquotes
Markdown uses email-style >
characters for blockquoting. If you’re
familiar with quoting passages of text in an email message, then you
know how to create a blockquote in Markdown. It looks best if you hard
wrap the text and put a >
before every line:
This is a blockquote with two paragraphs. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus.
Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse id sem consectetuer libero luctus adipiscing.
Markdown allows you to be lazy and only put the >
before the first
line of a hard-wrapped paragraph:
This is a blockquote with two paragraphs. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus.
Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse id sem consectetuer libero luctus adipiscing.
Blockquotes can be nested (i.e. a blockquote-in-a-blockquote) by
adding additional levels of >
:
This is the first level of quoting.
This is nested blockquote.
Back to the first level.
Blockquotes can contain other Markdown elements, including headers, lists, and code blocks:
This is a header.
- This is the first list item.
- This is the second list item.
Here’s some example code:
return shell_exec("echo $input | $markdown_script");
Any decent text editor should make email-style quoting easy. For example, with BBEdit, you can make a selection and choose Increase Quote Level from the Text menu.
Lists
Markdown supports ordered (numbered) and unordered (bulleted) lists.
Unordered lists use asterisks, pluses, and hyphens – interchangably – as list markers:
- Red
- Green
- Blue
is equivalent to:
- Red
- Green
- Blue
and:
- Red
- Green
- Blue
Ordered lists use numbers followed by periods:
- Bird
- McHale
- Parish
It’s important to note that the actual numbers you use to mark the list have no effect on the HTML output Markdown produces. The HTML Markdown produces from the above list is:
If you instead wrote the list in Markdown like this:
- Bird
- McHale
- Parish
or even:
- Bird
- McHale
- Parish
you’d get the exact same HTML output. The point is, if you want to, you can use ordinal numbers in your ordered Markdown lists, so that the numbers in your source match the numbers in your published HTML. But if you want to be lazy, you don’t have to.
To make lists look nice, you can wrap items with hanging indents:
- Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus.
- Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse id sem consectetuer libero luctus adipiscing.
But if you want to be lazy, you don’t have to:
- Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus.
- Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse id sem consectetuer libero luctus adipiscing.
List items may consist of multiple paragraphs. Each subsequent paragraph in a list item must be indented by either 4 spaces or one tab:
-
This is a list item with two paragraphs. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus.
Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus. Donec sit amet nisl. Aliquam semper ipsum sit amet velit.
-
Suspendisse id sem consectetuer libero luctus adipiscing.
It looks nice if you indent every line of the subsequent paragraphs, but here again, Markdown will allow you to be lazy:
-
This is a list item with two paragraphs.
This is the second paragraph in the list item. You’re only required to indent the first line. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
-
Another item in the same list.
To put a blockquote within a list item, the blockquote’s >
delimiters need to be indented:
-
A list item with a blockquote:
This is a blockquote inside a list item.
To put a code block within a list item, the code block needs to be indented twice – 8 spaces or two tabs:
-
A list item with a code block:
<code goes here>
Code Blocks
Pre-formatted code blocks are used for writing about programming or
markup source code. Rather than forming normal paragraphs, the lines
of a code block are interpreted literally. Markdown wraps a code block
in both <pre>
and <code>
tags.
To produce a code block in Markdown, simply indent every line of the block by at least 4 spaces or 1 tab.
This is a normal paragraph:
This is a code block.
Here is an example of AppleScript:
tell application "Foo"
beep
end tell
A code block continues until it reaches a line that is not indented (or the end of the article).
Within a code block, ampersands (&
) and angle brackets (<
and >
)
are automatically converted into HTML entities. This makes it very
easy to include example HTML source code using Markdown – just paste
it and indent it, and Markdown will handle the hassle of encoding the
ampersands and angle brackets. For example, this:
<div class="footer">
© 2004 Foo Corporation
</div>
Regular Markdown syntax is not processed within code blocks. E.g., asterisks are just literal asterisks within a code block. This means it’s also easy to use Markdown to write about Markdown’s own syntax.
tell application "Foo"
beep
end tell
Span Elements
Links
Markdown supports two style of links: inline and reference.
In both styles, the link text is delimited by [square brackets].
To create an inline link, use a set of regular parentheses immediately after the link text’s closing square bracket. Inside the parentheses, put the URL where you want the link to point, along with an optional title for the link, surrounded in quotes. For example:
This is an example inline link.
This link has no title attribute.
Emphasis
Markdown treats asterisks (*
) and underscores (_
) as indicators of
emphasis. Text wrapped with one *
or _
will be wrapped with an
HTML <em>
tag; double *
’s or _
’s will be wrapped with an HTML
<strong>
tag. E.g., this input:
single asterisks
single underscores
double asterisks
double underscores
Code
To indicate a span of code, wrap it with backtick quotes (`
).
Unlike a pre-formatted code block, a code span indicates code within a
normal paragraph. For example:
Use the printf()
function.
Summary
Ship it! Good enough for my needs :)
Cover Photo by Unseen Studio on Unsplash.