This commit is contained in:
Bob Farrell 2024-10-29 21:52:16 +00:00
parent e4e3b400b2
commit b07f5adb8c
3 changed files with 28 additions and 12 deletions

View File

@ -126,7 +126,11 @@ fn renderMarkdown(
) !?[]const u8 {
const path = try std.mem.join(allocator, "/", &[_][]const u8{ route.uri_path, @tagName(route.action) });
defer allocator.free(path);
const content = try jetzig.markdown.render(allocator, path, markdown_fragments) orelse return null;
const content = try jetzig.markdown.renderFile(
allocator,
path,
.{ .fragments = markdown_fragments },
) orelse return null;
if (route.layout) |layout_name| {
try view.data.addConst("jetzig_view", view.data.string(route.name));

View File

@ -274,7 +274,7 @@ fn renderMarkdown(self: *Server, request: *jetzig.http.Request) !?RenderedView {
_ = self;
// No route recognized, but we can still render a static markdown file if it matches the URI:
if (request.method != .GET) return null;
if (try jetzig.markdown.render(request.allocator, request.path.base_path, null)) |content| {
if (try jetzig.markdown.renderFile(request.allocator, request.path.base_path, .{})) |content| {
return .{
.view = jetzig.views.View{ .data = request.response_data, .status_code = .ok },
.content = content,

View File

@ -4,13 +4,29 @@ const Zmd = @import("zmd").Zmd;
const jetzig = @import("../jetzig.zig");
pub const MarkdownRenderOptions = struct {
fragments: ?type = null,
};
pub fn render(
allocator: std.mem.Allocator,
path: []const u8,
custom_fragments: ?type,
) !?[]const u8 {
const fragments = custom_fragments orelse jetzig.config.get(type, "markdown_fragments");
content: []const u8,
comptime options: MarkdownRenderOptions,
) ![]const u8 {
const fragments = options.fragments orelse jetzig.config.get(type, "markdown_fragments");
var zmd = Zmd.init(allocator);
defer zmd.deinit();
try zmd.parse(content);
return try zmd.toHtml(fragments);
}
pub fn renderFile(
allocator: std.mem.Allocator,
path: []const u8,
comptime options: MarkdownRenderOptions,
) !?[]const u8 {
var path_buf = std.ArrayList([]const u8).init(allocator);
defer path_buf.deinit();
@ -33,16 +49,12 @@ pub fn render(
else => err,
};
};
const markdown_content = std.fs.cwd().readFileAlloc(allocator, full_path, @intCast(stat.size)) catch |err| {
const content = std.fs.cwd().readFileAlloc(allocator, full_path, @intCast(stat.size)) catch |err| {
switch (err) {
error.FileNotFound => return null,
else => return err,
}
};
var zmd = Zmd.init(allocator);
defer zmd.deinit();
try zmd.parse(markdown_content);
return try zmd.toHtml(fragments);
return try render(allocator, content, options);
}