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

查看:22
本文介绍了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:

顺便提一下,我会考虑您是否真的想在模板层中进行数据访问.

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天全站免登陆