如何将请求 Header 从主视图传递到 Play 框架中的部分视图

How to pass Request Header from Main view to Partial View in Play framework

我有一个 Play 2 View 嵌入在 main 里面 div 如下

  1. @mainboard.applicationtraffic.render()

    上面的视图在顶部有一个定义为@(隐式请求:RequestHeader)的参数
    应用流量。因为我想使用 websocket,所以我定义了那个参数

    问题:当我尝试通过 1. 渲染时,它要求 RequestHeader 作为参数 谁能给我一些示例代码如何将请求header传递给部分视图
    渲染方法

    提前谢谢你

   
applicationtraffic.scala.html

@(implicit request: RequestHeader)

<script type="text/javascript">
var socket = new WebSocket("@routes.Application.applicationTrafficWS().webSocketURL()")
socket.onopen = function(event)
{
socket.send('I am the client and I\'m listening!');
socket.onmessage = function(event)
{
var datapoint = jQuery.parseJSON( event.data );
$("#data" ).html(datapoint);
};
socket.onclose = function(event)
{
console.log('Client notified socket has closed',event);
};
};
</script>
<div id="data">
  
</div>

Index.scala.html

    <div class="span4">
         <div class="widget" >
            <div class="widget-head">
                <h4 class="heading glyphicons cardio"><i></i>Application Traffic</h4>
                  </div>
                     <div class="widget-body">
                       @mainboard.applicationtraffic.render(Context.current.get()._requestHeader())
                  </div>
            </div>
     </div>

这是一个最小示例,说明如何通过将 request 作为隐式参数传递来获得您想要的内容。首先,您需要在 index.html:

中声明隐式参数

index.scala.html

@()(implicit request: play.api.mvc.RequestHeader)
<div class="span4">
  <div class="widget" >
    <div class="widget-head">
      <h4 class="heading glyphicons cardio"><i></i>Application Traffic</h4>
    /div>
    <div class="widget-body">
      @applicationtraffic()
    /div>
  </div>
</div>

请注意空参数列表以及调用局部视图的方式(我已删除此示例中的主板前缀,因为您将局部视图命名为 applicationtraffic.scala.html)。因为要隐式传递请求而我们没有显式参数,所以需要再次添加空括号:

applicationtraffic.scala.html

@()(implicit request: RequestHeader)

<script type="text/javascript">...</script>
<div>...</div>

最后,您的控制器方法应将 request 参数声明为 implicit

def index = Action { implicit request =>
  Ok(views.html.index())
}