Javascript的Mojolicious,布局和定位

use*_*233 2 javascript perl jquery mojo mojolicious

我想在我的主要布局中加载大部分脚本(即jquery).根据我的理解,最好将脚本放在我的html页面的底部.

但是,如果我们将脚本放在布局页面的底部,就像这样.

layout/default.html.ep

<!doctype html>

<html>
<head><title><%= title %></title></head>
<body><%=content %></body>
</html>
<script src="js/jquery.min.js" type="text/javascript"></script>    
Run Code Online (Sandbox Code Playgroud)

然后在一个页面中使用此布局,该页面具有自己的javascript,依赖于jquery.

testscript.html.ep
%layout 'default';
%title 'Script Test';

<p>Main Page</p>

<script type="text/javascript">
$(document).ready(function(){
alert('fails if jquery is not loaded');  
});
</script>
Run Code Online (Sandbox Code Playgroud)

你最终得到这样的页面.请注意,对jquery的引用低于我依赖它的代码.

<!doctype html>

<html>
<head><title>Script Test</title></head>
<body>
<p>Main Page</p>

<script type="text/javascript">
$(document).ready(function(){
alert('fails if jquery is not loaded');
});
</script>
<script src="js/jquery.min.js" type="text/javascript"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

处理这种情况的最佳方法是什么?

把我的javascript引用放在我的布局顶部?我假设在使用此布局的每个页面中添加jquery的脚本引用不是最佳做法?

任何帮助深表感谢.我非常喜欢这一切.

干杯.

Joe*_*ger 5

抱歉,我们错过了这个,大多数使用Mojolicious的人都遵循Perl标签.

要回答您的问题,请使用content_for帮助程序将内容放在您想要的位置.请注意,这也允许您将导入放在依赖模板的顶部,如果您愿意,也可以放在底部!我有一个例子如下.我还建议为所有页面都需要标准JS导入的单独模板,尽管这只是为了清楚起见.

#!/usr/bin/env perl

use Mojolicious::Lite;

any '/' => 'testscript';

app->start;

__DATA__

@@ layouts/default.html.ep

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
  </head>
  <body>
    %= content
    %= include 'common_js'
    %= content_for 'js_imports'
  </body>
</html>

@@ common_js.html.ep
<script src="js/jquery.min.js" type="text/javascript"></script>

@@ testscript.html.ep
%layout 'default';
%title 'Script Test';

% content_for 'js_imports' => begin
  %= javascript begin
    $(document).ready(function(){
      alert('fails if jquery is not loaded');  
    });
  % end
% end

<p>Main Page</p>
Run Code Online (Sandbox Code Playgroud)

当您访问'/'路线时,会产生

<!DOCTYPE html>
<html>
  <head>
    <title>Script Test</title>
  </head>
  <body>


<p>Main Page</p>

    <script src="js/jquery.min.js" type="text/javascript"></script>

      <script>//<![CDATA[

    $(document).ready(function(){
      alert('fails if jquery is not loaded');  
    });

//]]></script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)