Skip to content

How to receive an optional parameter in a component? #844

Answered by a-h
henriqueleite42 asked this question in Q&A
Discussion options

You must be logged in to vote

Yes, there's a couple of ways. templ just creates a Go function, so it's the same as Go.

templ.Component is an interface, so it can be nil.

templ DefaultLayout(title string, head templ.Component) {
	<!DOCTYPE html>
	<html lang="pt-br">
		<head>
			<meta charset="UTF-8"/>
			<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
			<title>{ title }</title>
			if head != nil {
				@head
			}
		</head>
		<body>
			{ children... }
		</body>
	</html>
}

Use a struct to take params

type DefaultLayoutProps {
	Title string
	Head templ.Component
}

templ DefaultLayout(props DefaultLayoutProps) {
	<!DOCTYPE html>
	<html lang="pt-br">
		<head>
			<meta charset="UTF-8"/>
			<meta name="

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@henriqueleite42
Comment options

Answer selected by henriqueleite42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants