name: Global Variables

sort: 5

Global Variables

Variables common to all requests can be added using a base controller using the Prepare method.

Usage examples include the username of the current user for display in a toolbar or the request URL for highlighting active menu items.

First, create a common/base controller in the controllers package:

  1. app_root
  2. ├── controllers
  3. ├── base.go <-- base controller
  4. └── default.go
  5. └── main.go

Your base controller should embed the web.Controller from github.com/beego/beego/v2/server/web. From here, the Prepare method should be defined, containing any logic required for global variables:

  1. // app_root/controllers/base.go
  2. package controllers
  3. import (
  4. "github.com/beego/beego/v2/server/web"
  5. )
  6. type BaseController struct {
  7. web.Controller
  8. }
  9. // Runs after Init before request function execution
  10. func (c *BaseController) Prepare() {
  11. c.Data["RequestUrl"] = c.Ctx.Input.URL()
  12. }
  13. // Runs after request function execution
  14. func (c *BaseController) Finish() {
  15. // Any cleanup logic common to all requests goes here. Logging or metrics, for example.
  16. }

All other controllers should embed BaseController instead of web.Controller:

  1. // app_root/controllers/default.go
  2. package controllers
  3. type DefaultController struct {
  4. BaseController
  5. }
  6. func (c *DefaultController) Index() {
  7. // your controller logic
  8. }

From here your views can access these global variables, in both individual templates and all parent templates:

  1. <div>{{ $.RequestUrl }}</div>