Skip to content

Commit cde93ca

Browse files
authored
docs(techniques/mvc): introduce @WithAlias() decorator
Documents the @WithAlias() decorator and getUrl helper introduced in PR nestjs/nest#5117
1 parent 2bba05b commit cde93ca

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

content/techniques/mvc.md

+36
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,42 @@ In this code, we are specifying the template to use in the `@Render()` decorator
9494

9595
While the application is running, open your browser and navigate to `http://localhost:3000`. You should see the `Hello world!` message.
9696

97+
#### Aliasing Routes
98+
99+
You can alias routes with the `@WithAlias()` decorator in your controller, and then reference the alias inside your view.
100+
101+
Suppose in your user controller, you have some routes to a list of users or to a specific user:
102+
```typescript
103+
@@filename(users.controller)
104+
import { Get, Controller, Render, WithAlias } from '@nestjs/common';
105+
import { User } from './user.entity.ts';
106+
107+
@Controller('users')
108+
export class UserController {
109+
@Get()
110+
@Render('users-list')
111+
@WithAlias('hello')
112+
root(): User[] {
113+
return [ /* list of users */ ];
114+
}
115+
116+
@Get('/:user')
117+
@Render('user')
118+
@WithAlias('hello')
119+
getUser(): User {
120+
return { /* user */ }
121+
}
122+
}
123+
```
124+
Once you have registered route aliases, you can access them via the `getUrl(routeAlias: string, routeParams?: object): string` method that is injected into the template render context.
125+
126+
```njk
127+
<a href="{{ getUrl('users-list') }}">Users</a>
128+
<a href="{{ getUrl('user', { user: user.id }) }}">User With Specific ID</a>
129+
```
130+
131+
> warn **Note** Some templating engines (like handlebars) do not support evaluation of functions inside your template.
132+
97133
#### Dynamic template rendering
98134

99135
If the application logic must dynamically decide which template to render, then we should use the `@Res()` decorator, and supply the view name in our route handler, rather than in the `@Render()` decorator:

0 commit comments

Comments
 (0)