forked from jooby-project/jooby
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebVariables.java
More file actions
69 lines (61 loc) · 1.69 KB
/
WebVariables.java
File metadata and controls
69 lines (61 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* Jooby https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby;
import javax.annotation.Nonnull;
/**
* Add common variables to as {@link Context} attributes so they are accessible from template
* engine.
*
* Usage:
*
* <pre>{@code
* decorator(new WebVariables());
*
* get("/", ctx -> new ModelAndView("index.ftl"));
* }</pre>
*
* Template engine will be able to access to the following attributes:
*
* - contextPath. Empty when context path is set to <code>/</code> or actual context path.
* - path. Current request path, as defined by {@link Context#getRequestPath()}.
* - user. Current user (if any) as defined by {@link Context#getUser()}.
*
* @author edgar
* @since 2.4.0
*/
public class WebVariables implements Route.Decorator {
private final String scope;
/**
* Creates a web variables under the given scope.
*
* @param scope Scope to use.
*/
public WebVariables(@Nonnull String scope) {
this.scope = scope;
}
/**
* Creates a new web variables.
*/
public WebVariables() {
this.scope = null;
}
@Nonnull @Override public Route.Handler apply(@Nonnull Route.Handler next) {
return ctx -> next.apply(webvariables(ctx));
}
private Context webvariables(Context ctx) {
String contextPath = ctx.getContextPath();
ctx.attribute(key("contextPath"), contextPath.equals("/") ? "" : contextPath);
ctx.attribute(key("path"), ctx.getRequestPath());
Object user = ctx.getUser();
if (user != null) {
ctx.attribute(key("user"), user);
}
return ctx;
}
private String key(String key) {
return scope == null ? key : scope + "." + key;
}
}