express-tsx-views
express-tsx-views copied to clipboard
Default layout / specify layout in render method.
I'm moving from using EJS / HBS to TSX and have been experimenting with this package and it works really well for my use case.
One shortcoming is I can use a default view (main) or specify another in the render method with HbS/EJS. This is very handy when I have a module that houses its own views but may get plugged in to multiple projects with their own master layouts / views.
I'm wondering if the path to a layout might be defined as part of the context which could then be passed through the render method. I think I can achieve it with some "hackery" as is, but it would be nice if it was baked in to allow a default view and view override.
I guess this might force a particular pattern on to views to enable them to accept the layout.
I got this working in a very crude manner. At the minute I have to ensure all my views are wrapped in the LayoutContainer that then uses context to determine what layout to load the view within.
I think it would be cleaner if I could create my views and layouts separately and have the TSX-views engine piece it together using the default view specified in config, or passed view the render method.
export default function LayoutContainer(props: any): ReactElement {
const context = useContext(DefaultContext);
let LayoutComponent;
if (context.layout) {
try {
const module = require(context.layout);
LayoutComponent = module.default;
} catch (error) {
console.log(`Error loading layout '%s'`, context.layout)
}
}
return LayoutComponent ? <LayoutComponent>{props.children}</LayoutComponent> : <>{props.children}</>;
}
Another thought I had was if there was a mechanism to have context globally available to views. For example res.locals. not played with this yet, but I think again if the TSX engine should perhaps have a default context that it makes available.