Play Framework 2.4在Scala模板中使用注入变量 [英] Play Framework 2.4 use injected variable in Scala template

查看:99
本文介绍了Play Framework 2.4在Scala模板中使用注入变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的网页菜单栏中显示来自数据库的一些数据.为了获取数据,我有一个通常通过Guice注入创建的数据访问对象(DAO).

I would like to show some data from the database in the menubar of my web page. To get the data, I have a data-access-object (DAO) which is usually created with Guice injection.

如何在我的Scala模板中使用这样的(注入的)对象?

我可以将它作为参数传递给模板,但是我必须在每个页面上都这样做(因为它应该显示在菜单栏中).我正在寻找另一种解决方案,无需在任何地方传递它.当前,无论何时呈现模板,我都会在模板内创建一个新对象(这使我的代码更简洁,但性能却较差).

I could pass it as a parameter to the template, but I had to do this on every single page (because it should be displayed in the menubar). I'm looking for another solution where I don't have to pass it everywhere. Currently I'm creating a new object inside the template, whenever it is rendered (which gets me a cleaner code but a worse performance).

推荐答案

您可以毫不费力地对它进行伪造.

You can kinda-sorta fake this without too much effort.

首先,创建一个提供对DAO的访问权限的Scala对象(该对象可以包含任意数量的内容,只需在顶级对象和Implicits对象中重复该模式即可.)

First, create a Scala object that provides access to your DAO (this can contain as many things as you want, just repeat the pattern within the top-level object and the Implicits object).

package com.example.stuff

object ViewAccessPoint {
  private[stuff] val myDaoCache = Application.instanceCache[MyDao]

  object Implicits {
    implicit def myDao(implicit application: Application): MyDao = myDaoCache(application)
  }
}

在您看来,然后可以将Implicits对象导入模板并获得Guice创建的DAO.

In your view, you can then import the Implicits object into your template and get hold of the DAO created by Guice.

@import com.example.stuff.ViewAccessPoint.Implicits._
@import play.api.Play.current

myDao.whatever()

这同时适用于Java和Scala项目.

This works for both Java and Scala projects.

您可以在这里在实践中看到这一点:

You can see this in practice here:

  • Access point
  • Template

另一方面,我会考虑您是否真的想在模板层中进行数据访问.

On a side note, I would consider if you really want to be doing data access in your template layer.

这篇关于Play Framework 2.4在Scala模板中使用注入变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆