Skip to content
MohammadAli Arjomand edited this page Sep 6, 2023 · 6 revisions

SinglightJs has a simple and powerful router

All routes, is in ~/Scripts/Router.js file

Add Route

It's a super-easy method! you only must pass a url and a page

router.addRouter("/", HomePage);

You can add any routes to it

router.addRouter("/", HomePage);
router.addRouter("/posts", PostsIndexPage);

You can use variables in routes

router.addRouter("/", HomePage);
router.addRouter("/posts", PostsIndexPage);
router.addRouter("/posts/{id}", PostShowPage);

And you can set names for routes

router.addRouter("/", HomePage, "home");
router.addRouter("/posts", PostsIndexPage, "posts.index");
router.addRouter("/posts/{id}", PostShowPage, "posts.show");

Set Root

If you are using urls like http://example.com, https://example.com, https://sub.example.com, https://example.com:8000 or anythings like than as root, router was working ok! but if your url root is like https://example.com/directory/nested you get 404 Error to every routes. For fix this error you must use setRoot and pass nested directory to than

router.setRoot("/directory/nested");

NOTICE setRoot must be before every addRoute

Route Groups

When you have a many routes like /posts, /posts/{id}, /posts/create, /posts/{id}/edit, /posts/{id}/destroy, etc. you can use Route groups

The first argument of addRouteGroup is the prefix and second argument is a closure (arrow function) to contains addRoute

router.addRouteGroup("/posts", router => {
    router.addRoute("/", PostsIndexPage); // -> /posts
    router.addRoute("/{id}", PostShowPage); // -> /posts/{id}
    router.addRoute("/create", PostCreatePage); // -> /posts/create
    router.addRoute("/{id}/edit", PostEditPage); // -> /posts/{id}/edit
    router.addRoute("/{id}/destroy", PostDestroyPage); // -> /posts/{id}/destroy
    return router;
});

NOTICE you must return router after adding routes in route groups

Custom Errors

With addRouteError you can create custom 404 and 403 error pages

router.addRouteError(404, NotFoundPage);
router.addRouteError(403, ForbiddenPage);
Clone this wiki locally