S&box Wiki

Revision Difference

ui-razor-templates#550374

<cat>UI.Razor</cat> <title>Templates</title> # Templates Templates allow you to define some content to show inside another razor file. This makes it easy to make components more agile and reusable. Here's a simple example, here's `InfoCard.razor` ```html <root> <div class="header">@Header</div> <div class="body">@Body</div> <div class="footer">@Footer</div> </root> @code { public RenderFragment Header { get; set; } public RenderFragment Body { get; set; } public RenderFragment Footer { get; set; } } ``` Then you can use this in other components like this ```html <root> <InfoCard> <Header>My Card</Header> <Body> <div class="title">This is my card</div> </Body> <Footer> <div class="button" onclick="@CloseCard">Close Card</div> </Footer> </InfoCard> </root> @code { void CloseCard() { Delete(); } } ``` As you can see, we're defining the insides of the InfoCard panel. We can even add events and functions that add interactions from the parent panel. # With Arguments RenderFragment<T> is used to define a fragment that takes an argument. Here's how it works, here's `EntityList.razor` ``` @using Sandbox; <root> @foreach ( var entity in EntityList.Take( 10 ) ) { <div class="row"> @EntityRow( entity ) </div> } </root> @code { public List<Entity> EntityList { get; set; } public RenderFragment<Entity> EntityRow { get; set; } } ``` As you can see we're now defining `EntityRow` that takes an argument. To call it we just call it like a function, with the entity argument. Now to use `EntityList` we do this ``` @using Sandbox; <root> <EntityList EntityList="@MyEntityList"> <EntityRow Context> @if (context is not Entity entity) return; <div class="row">@entity.Name</div> <div class="row">@entity.Health</div> </EntityRow> </EntityList> </root> @code { List<Entity> MyEntityList; } ``` In the EntityRow we add the special attribute `Context`, which tells our code generator that this is going to need a special `object context`. Then in the fragment, we can convert this `object` into our target type. Then you're free to use it as you wish. ⤶ # Elements inside components⤶ ⤶ All panels have a render fragment called ChildContent, so you can add elements inside of any component without adding your own.⤶ ⤶ ```html⤶ <InfoCard>⤶ <ChildContent>⤶ <label>something inside of InfoCard</label>⤶ </ChildContent>⤶ </InfoCard>⤶ ```