Skip to content

How to Build a Grav Plugin: Part 2

Sketching out the shortcode syntax

  • code
  • tutorial
  • series

In part 1 of this series, I covered identifying the need and desired features of this project. To recap:

I’ve used shortcodes elsewhere in the theme I developed for my 2021 site redesign.for blockquotes, and for these toggleable notes — they function a bit like extended parenthetical remarks, or asides

Shortcode syntax ideas

Design decision time: the highlight.php library supports autodetection of the language in a given fragment. I’m not going to. Instead, I’d rather be explicit about the language in every case like in the following. There are two kinds of cases — inline and block content — each with different levels of verbosity:

  1. Self-closing shortcodes for very short snippets in flow content:

    • Minimal version, with the language tag and the snippet as a BBCode fragment:

      [js=console.log('hey') /]

    • Self-closing, inline form, with specific language tag and @ syntax to specify the code text:

      [js @=console.log('hey') /]

    • Self-closing, inline form, with generic hl tag, lang given as a BBCode fragment, and @ syntax to specify the code text:

      [hl=js @=console.log('hey') /]

    • Self-closing, inline form, with generic hl tag, lang given as a parameter, and @ syntax to specify the code text:

      [hl lang=js @=console.log('hey') /]

The above should all result in console.log('hey').

  1. Paired shortcodes for longer code samples to be set as block content, wrapped in a pre tag:

    • Paired shortcodes, with specific language tag:

      [python]
      def greet(name):
          print(f"Hi, {name}!")
      [/python]
    • Paired shortcodes, with generic hl tag and lang given as BBCode fragment:

      [hl=python]
      def greet(name):
          print(f"Hi, {name}!")
      [/hl]
    • Paired shortcodes, with generic hl tag and lang parameter:

      [hl lang=python]
      def greet(name):
          print(f"Hi, {name}!")
      [/hl]

The above should all result in:

def greet(name):
    print(f"Hi, {name}!")

I like the brevity of using the language identifier itself as the tag name, so that’s probably what I’ll use. The rest of the alternatives are in keeping with existing shortcodes provided by Grav’s shortcode core plugin, including that alternative syntaxes and optional parameters are allowed.

Cool. That’s a wrap. Next up: setting up a development environment.