statiqdev / Statiq.Framework

A flexible and extensible static content generation framework for .NET.
https://statiq.dev/framework
MIT License
425 stars 74 forks source link

How to render a Razor View Component? #230

Open betfix opened 2 years ago

betfix commented 2 years ago

I created a console app with Statiq.Web, the CleanBlog theme and a few pages. Then I added a class named "CategoriesViewComponent" at project root and added this line to _layout.cshtml:

@await Component.InvokeAsync("Categories")
//or @await Component.InvokeAsync(typeof(MyProject.CategoriesViewComponent))

This causes the app to throw error:

[ERRO] Content/PostProcess » RenderContentPostProcessTemplates » ExecuteIf » ExecuteIf » RenderRazor » [D:/MyProjects/MyProject/MyProject/input/home.cshtml => home.html] A view component named 'Categories' could not be found. A view component must be a public non-abstract class, not contain any generic parameters, and either be decorated with 'ViewComponentAttribute' or have a class name ending with the 'ViewComponent' suffix. A view component must not be decorated with 'NonViewComponentAttribute'.

The view component class is there and fulfills the conditions for being a view component. Is it possible to make it visible to Razor engine when running from Statiq?

daveaglick commented 2 years ago

In theory I think component support should be possible. Statiq uses the ASPNET Core 3.x Razor engine, so anything that works there should be capable of working here. The challenge is that just having the engine isn't enough - it takes a fair bit of reflection and hacking to light up various features.

So far I've focused on common functionality like layouts, partials, and tag helpers. It's likely component support is possible with a little more hacking, but it's not a feature I've tested or directly supported so far.

I'm dedicating most of my brain cells to getting Statiq Docs out the door right now. I'll try to take a look at Razor components at some point this week - if it's easy enough to light up, I'll add it to the next release. If not, support for components may need to wait on the backlog for a while until I (or someone else) can get to it and figure out what's not working.

daveaglick commented 2 years ago

Transferring this issue to Statiq Framework since that’s where Razor support lives.