Play Framework 2.4 在 Scala 模板中使用注入的变量

编程入门 行业动态 更新时间:2024-10-21 07:36:24
本文介绍了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屋!

更多推荐

[db:关键词]

本文发布于:2023-03-27 09:50:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/686688.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   模板   Framework   Play   Scala

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!