From 2e9cbbbcec1329cf8222b3273126f0415a243e55 Mon Sep 17 00:00:00 2001 From: eunjeong Park Date: Sat, 16 Aug 2025 12:45:44 +0900 Subject: [PATCH] Add fallback to default language for code_sample shortcode This imporves internationalization support by falling back to the default language's examples when a translation doesn't exist, prevention build errors for missing localized code samples. - Refactor code_sample.html to handle missing files more gracefully - Move filename generation to scratch variable for reusability - Add fallback logic to try default language when file not found in current language - Reorganize source lookup flow with proper conditional blocks - Maintain existing ghlink generation with updated filename variable --- layouts/shortcodes/code_sample.html | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/layouts/shortcodes/code_sample.html b/layouts/shortcodes/code_sample.html index fda3a27f13..852c9df8a5 100644 --- a/layouts/shortcodes/code_sample.html +++ b/layouts/shortcodes/code_sample.html @@ -3,20 +3,26 @@ {{ $codelang := .Get "language" | default (path.Ext $file | strings.TrimPrefix ".") }} {{ $fileDir := path.Split $file }} {{ $bundlePath := path.Join .Page.File.Dir $fileDir.Dir }} -{{ $filename := printf "/content/%s/examples/%s" .Page.Lang $file | safeURL }} -{{ $ghlink := printf "https://%s/%s%s" site.Params.githubwebsiteraw (default "main" site.Params.docsbranch) $filename | safeURL }} +{{ $.Scratch.Set "filename" (printf "/content/%s/examples/%s" .Page.Lang $file) }} {{/* First assume this is a bundle and the file is inside it. */}} -{{ $resource := $p.Resources.GetMatch (printf "%s*" $file ) }} -{{ with $resource }} +{{ with $p.Resources.GetMatch (printf "%s*" $file) }} {{ $.Scratch.Set "content" .Content }} -{{ else }} +{{ end }} {{/* Read the file relative to the content root. */}} -{{ $resource := readFile $filename}} -{{ with $resource }}{{ $.Scratch.Set "content" . }}{{ end }} +{{ with readFile ($.Scratch.Get "filename")}} +{{ $.Scratch.Set "content" . }} +{{ end }} +{{/* If not found, try the default language */}} +{{ $defaultLang := (index (sort site.Languages "Weight") 0).Lang }} +{{ with readFile (printf "/content/%s/examples/%s" $defaultLang $file) }} +{{ $.Scratch.Set "content" . }} +{{ $.Scratch.Set "filename" (printf "/content/%s/examples/%s" $defaultLang $file) }} {{ end }} {{ if not ($.Scratch.Get "content") }} {{ errorf "[%s] %q not found in %q" site.Language.Lang $fileDir.File $bundlePath }} {{ end }} +{{ $filename := printf ($.Scratch.Get "filename") | safeURL }} +{{ $ghlink := printf "https://%s/%s%s" site.Params.githubwebsiteraw (default "main" site.Params.docsbranch) $filename | safeURL }} {{ with $.Scratch.Get "content" }}