Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to route to a function that builds a component #562

Closed
wants to merge 1 commit into from

Conversation

aopal
Copy link

@aopal aopal commented Jul 22, 2021

Adds new public methods RouteFactory and RouteWithRegexpFactory that allow a developer to specify a function to build a new component when a route is matched. This is intended to allow the creation of powerful generic components, example below.

type Page struct {
	app.Compo
	pageContent app.Composer
}

func (p *Page) Render() app.UI {
	return app.Div().Body(
		newNavBar(), // imagine a `type NavBar struct { app.Compo ...}` somewhere
		p.pageContent,
	)
}

func pageFor(cf app.ComposerFactory) app.ComposerFactory {
	return func() app.Composer {
		return &Page{
			pageContent: cf(),
		}
	}
}

type User struct {
	app.Compo
	name  string
	posts []BlogPost
}

func (u *User) Render() app.UI {
	return app.Div().Body(
		app.H1().Body(
			app.Text(u.name),
		),
		app.Range(u.posts).Slice(func(i int) app.UI {
			return app.A().Href(fmt.Sprintf("/post/%s", u.posts[i].title)).Body(
				app.Text(u.posts[i].title),
			)
		}),
	)
}

func newUser() app.Composer {
	return &User{}
}

type BlogPost struct {
	app.Compo
	title string
	body  string
}

func (bp *BlogPost) Render() app.UI {
	return app.Div().Body(
		app.H1().Body(
			app.Text(bp.title),
		),
		app.P().Body(
			app.Text(bp.body),
		),
	)
}

func newBlogPost() app.Composer {
	return &BlogPost{}
}

func main() {
	app.RouteWithRegexpFactory("^/user/[0-9]+$", pageFor(newUser))
	app.RouteWithRegexpFactory("^/post/\\w+$", pageFor(newBlogPost))
	app.RunWhenOnBrowser()

	http.Handle("/", &app.Handler{
		Name:        "Blog",
		Description: "An example blogging site",
	})

	if err := http.ListenAndServe(":8000", nil); err != nil {
		log.Fatal(err)
	}
}

@maxence-charriere
Copy link
Owner

Hello there, sorry for the late answer.

I started to build v9.7.0 and took inspiration from this PR. Thank you so much for this!

@aopal aopal closed this Feb 13, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants