Shortcodes using cshtml #129
-
Is there some way to define a shortcode using a cshtml file or similar? Other static site engines have such a feature, where you set up your shortcodes in some special directory for example, and use html with templating to define them. Having to build the dom hierarchy manually in C# code is a bit of a hassle IMO. Thanks for your time! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Yes. Here's an example of how I implemented a custom shortcode to add an edit link to my pages: // This part is optional. It just makes sure the name is always constant.
public static class Constants
{
public const string EditLink = nameof(EditLink);
} public class Program
{
public static void Main()
{
var bootstrapper = Bootstrapper
.Factory
.CreateWeb(args)
.AddShortcode(Constants.EditLink,
(content, parameters, document, context)
=> document[Constants.EditLink] is string editLink ? editLink : "https://github.com/LuzFaltex/luzfaltex.com");
.RunAsync();
}
} <!-- _MasterLayout.cshtml -->
<!-- Code omitted for brevity -->
<li>
@if (Document[Constants.EditLink] is string editLink)
{
<a class="is-push-right" href="@editLink" target="_blank" rel="noreferer noopener" style="text-decoration: none"><i class="fal fa-pencil-alt" aria-hidden="true"></i> Improve this page</a>
}
</li> # settings.yml
EditLink: => "https://github.com/LuzFaltex/luzfaltex.com/blob/main/input/" + doc.Source.GetRelativeInputPath() By setting a default in your settings.yml or whatever configuration file you use, it allows for a sane fallback that you can override per-document as needed simply by adding front matter for EditLink. |
Beta Was this translation helpful? Give feedback.
-
I think the closest you're going to get to HTML-based components right now is Razor partials. Because Markdown accepts arbitrary HTML elements, and Statiq passes rendered Markdown on to a Razor processor, you should be able to call a partial by wrapping it in an HTML element. Something like:
And then in
I think this would all work the way I've described, but let me know if it doesn't. Admittedly the syntax at the call site in Markdown isn't great either, but that's probably the closest you're going to get without writing a shortcode. |
Beta Was this translation helpful? Give feedback.
I think the closest you're going to get to HTML-based components right now is Razor partials. Because Markdown accepts arbitrary HTML elements, and Statiq passes rendered Markdown on to a Razor processor, you should be able to call a partial by wrapping it in an HTML element. Something like:
And then in
_EditLink.cshtml
you could have something like: