How to embed you GitHub code to Hugo using a shortcode?

This article explains how to embed your GitHub code in your Hugo website using a shortcode.

Create the shortcode

Let’s create a new shortcode. In your Hugo site’s layouts/shortcodes directory (if the folder shortcodes does not exist create it manually), create a file called embedgithubcode.html and paste the following:

 1{{ $file := .Get 0 }}
 2{{ with resources.GetRemote $file }}
 3  {{ with .Err }}
 4    {{ errorf "%s" . }}
 5  {{ else }}
 6    {{ $lang := path.Ext $file | strings.TrimPrefix "." }}
 7    {{ highlight .Content $lang }}
 8  {{ end }}
 9{{ else }}
10  {{ errorf "Unable to get remote resource." }}
11{{ end }}

Use the shortcode

In any markdown file, you can now use the shortcode like this (note the space I added between {{ to prevent hugo from rendering the shortcode on this page):

(Note the space I added between {{ to prevent hugo from rendering the shortcode on this page):

1{ {< embedgithubcode "https://raw.githubusercontent.com/Benoit-Gaumard/azure-policy-aliases-outgridview/refs/heads/main/azure-policy-aliases-outgridview.ps1" >}}

Here is the result

The script is displayed from my github repository https://github.com/Benoit-Gaumard/azure-policy-aliases-outgridview :

 1# List all namespaces available in Azure Policy
 2$AllNamespaces = (Get-AzPolicyAlias -ListAvailable).Namespace | Sort-Object | Get-Unique
 3
 4# Select the namespaces you want to work with
 5$SelectedNamespaces = $null
 6$SelectedNamespaces = @()
 7
 8$AllNamespaces | Out-GridView -Title "Select one or more namespace. Found: $($AllNamespaces.count)" -OutputMode Multiple `
 9| Foreach-object { $SelectedNamespaces += $_ }
10
11# Get all aliases available in the selected namespaces
12$AvailableAliases = $null
13$AvailableAliases = @()
14
15Foreach ($Namespace in $SelectedNamespaces)
16{
17   $AvailableAliases += (Get-AzPolicyAlias -NamespaceMatch $Namespace).Aliases | Select-Object Name
18}
19
20# List all aliases available in the selected namespaces
21$AvailableAliases | Out-GridView -Title "Available alias for selected ($($SelectedNamespaces.count)): $($SelectedNamespaces)" -OutputMode Single

Enjoy!