dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
https://asp.net
MIT License
35.43k stars 10.02k forks source link

Rendering razor components outside of asp.net using HtmlRenderer ignores @layout directive #55068

Open Cherepoc opened 6 months ago

Cherepoc commented 6 months ago

Is there an existing issue for this?

Describe the bug

Hi! I'm using Razor components in my non-asp.net library to render emails. I've used this article to setup the project https://learn.microsoft.com/en-us/aspnet/core/blazor/components/render-components-outside-of-aspnetcore?view=aspnetcore-8.0 Everything works fine except for the @layout directive - it does not work at all, with or without @page directive. I've found a workaround - using LayoutView component does the job, but it would be so much cleaner to use the @layout directive, any chance it's possible?

Expected Behavior

@layout directive is not ignored when rendering Razor components with the HtmlRenderer, and the component is correctly rendered with the layout

Steps To Reproduce

Example project: https://github.com/Cherepoc/razor-layout-example Run the example. The project renders two components to the console. Both components write "Hello World", and both have a layout that writes "This is layout" before and after the hello world text. To use the layout, the first component uses the @layout directive, the other uses the LayoutView. The first component only outputs the "Hello world" text, without the layout text. The second component is rendered correctly.

Exceptions (if any)

No response

.NET Version

8.0

Anything else?

No response

mkArtakMSFT commented 6 months ago

Thanks for contacting us. This is currently not supported. Please avoid using layouts for now. You can try to render a component, which renders a layout view, but we're going into "custom solutions" area. People on StackOverflow may be able to suggest some other creative solutions for this. In the meantime, we'll park this in our Backlog to see how much interest this will generate from the community over time.

leonidk101 commented 4 months ago

I was using HtmlRenderer to generate email templates. @layout feature would be very useful. Didn't find any "Custom Solution" on StackOverflow. The only solution that comes to my mind is to render layout and component and manually merge two strings, but that's a hack.

Cherepoc commented 4 months ago

@leonidk101 LayoutView works.

<LayoutView Layout="typeof(LayoutType)">
    Hello World
</LayoutView>
leonidk101 commented 4 months ago

@leonidk101 LayoutView works.

<LayoutView Layout="typeof(LayoutType)">
    Hello World
</LayoutView>

Thanks @Cherepoc, that works!