Add images next to content

Register an asset folder so images beside your Markdown are served live and copied into the export.

On this page
Program.cscsharp
builder.AddBevel(options =>
{
    options.AssetFolders.Add(new("Data/Posts", "/posts", "*.png", "*.jpg", "*.svg", "*.webp"));
});
text
Data/Posts/my-post/index.md      -> page at /posts/my-post     (the folder is the slug)
Data/Posts/my-post/diagram.svg   -> file at /posts/my-post/diagram.svg

Put images in the post's folder and register the folder once.

How asset folders work

BevelOptions.AssetFolders is a list of BevelAssetFolder(Source, RequestPath, params Patterns).

  • Source is relative to the content root (or absolute). RequestPath starts with / (a trailing / is dropped). Neither includes PathBase.
  • At least one pattern is required. There is no default, so index.md and .cs files are never published.
  • Patterns are file globs. They match at any depth (a pattern without / gets **/) and ignore case.
  • Only files that match are served. Everything else, hidden files and directory listings are 404.
  • Asset folders are not data. The data step never reads them.

Live and exported behavior

  • Live. Bevel serves the folder with static-file middleware that it adds after your pipeline, in every environment. UsePathBase and Bevel pages come first. Content types follow UseStaticFiles. The source folder is the source of truth.
  • Export. Bevel copies each match to <output>/<RequestPath>/<relative path> and never prefixes the path base. It records the files in .bevel-output.json, so Bevel removes them when you delete the source. They count in BevelExportResult.AssetsCopied and in the "assets" figure in the export log and stats.

Fix validation and collision errors

Bevel validates folders at startup and on export. The source must exist, patterns must not contain .., and the source must not overlap the web root.

A collision fails the export before anything is written. The message names both sides:

  • an asset and a page route,
  • two assets,
  • an asset and a wwwroot file.

Paths that differ only by case follow the same rule as routes.

Bevel never follows symbolic links (or Windows reparse points), whether a file or any directory below the source. Linked files get 404, are not exported, and the export logs each skipped link once. The source folder itself may be a link.

Rewrite relative image URLs

A page at /posts/my-post has no trailing slash. A browser resolves ![x](diagram.svg) to /posts/diagram.svg, which is wrong. Hosts that redirect to /posts/my-post/ (GitHub Pages) make it work. Bevel's own server does not.

To be safe everywhere, and under PathBase or FlatHtml, rewrite relative image URLs in the component that renders your Markdown:

csharp
// html: the rendered post; slug: the post's slug; links: ISiteLinks
static string RewriteImages(string html, string slug, ISiteLinks links) =>
    System.Text.RegularExpressions.Regex.Replace(html, "(<img[^>]*?\\ssrc=\")(?![a-z]+:|/)([^\"]+)\"",
        m => m.Groups[1].Value + links.Asset("/posts/" + slug + "/") + m.Groups[2].Value + "\"");

The sample blog does this in its Markdown component:

samples/Bevel.SampleBlog/Components/Markdown.razorrazor
@using System.Text.RegularExpressions
@inject IBlogMarkdown Renderer

@if (TableOfContents && _rendered.Headings.Any(h => h.Level <= 3))
{
  <nav class="toc" aria-label="On this page">
    <h2>
      <Icon Name="toc"/>
      On this page
    </h2>
    <ol>
      @foreach (var h in _rendered.Headings.Where(x => x.Level <= 3))
      {
        <li class="toc-level-@h.Level">
          <a href="#@h.Id">@h.Text</a>
        </li>
      }
    </ol>
  </nav>
}

<div class="prose">
  @((MarkupString)Rewrite(_rendered.Html))
</div>

@code {

  /// <summary>The Markdown to render.</summary>
  [Parameter]
  public string Content { get; set; } = string.Empty;

  /// <summary>Renders an "On this page" list of the body's headings (levels 1–3) above it.</summary>
  [Parameter]
  public bool TableOfContents { get; set; }

  /// <summary>
  ///   URL (with a trailing slash) that relative image links resolve against, usually the post's folder such as
  ///   <c>Links.Asset("/posts/my-post/")</c>. Bevel pages have no trailing slash (<c>/posts/my-post</c>), so a bare
  ///   <c>how-it-works.svg</c> would otherwise resolve to <c>/posts/how-it-works.svg</c>; this also adds the PathBase.
  /// </summary>
  [Parameter]
  public string? AssetBase { get; set; }

  // Parsed once per parameter set; the table of contents and the body share it, so their ids always match.
  private RenderedMarkdown _rendered = default!;

  protected override void OnParametersSet() => _rendered = Renderer.Render(Content);

  private string Rewrite(string html) =>
    AssetBase is null
      ? html
      : Regex.Replace(html, "(<img[^>]*?\\ssrc=\")(?![a-z][a-z0-9+.-]*:|/|#)([^\"]+)\"",
        m => $"{m.Groups[1].Value}{AssetBase}{m.Groups[2].Value}\"", RegexOptions.IgnoreCase);

}