2013-02-23 98 views
1

如果我使用渲染相对路径渲染()

$app->render("./somewhere/index.html"); 

echo "<html>...</html>"; 

与外部的依赖关系(的JavaScript/CSS)的实际HTML网站出于某种原因苗条不能解决依赖路径 - 所以该网站无法正确加载。解决方法是$ app-> redirect(“./ somewhere/index.html”);而不是$ app-> render(“./ somewhere/index.html”); - 但随后浏览器地址栏中的URL路径也发生变化。我想避免这种情况,因为我只想显示我从URI接收到的REST请求的HTML模板 - 所以没有必要重定向到html文档并丢失REST参数。

我的问题的SSCCE:

目录结构:

- index.php 
+ templates 
|-- index.html 
|-- dependency.js 
+ Slim 
|-- ... 
|-- ... 

的index.php:

<?php 
require 'Slim/Slim.php'; 
\Slim\Slim::registerAutoloader(); 
$app = new Slim\Slim(); 
$app->get('/:id', function ($id) use ($app) { 
    $app->render('index.html'); 
}); 
$app->run(); 
?> 

/templates/index.html:

<html> 
<head> 
    <title>SSCCE</title> 
    <script id="someid" type="text/javascript" src="dependency.js"></script> 
</head> 
<body> 
    <a href="javascript:func_test()">Click here</a> 
</body> 
</html> 

/templates/dependency.js:

function func_test() { 
    alert("Test"); 
} 

1.)成功: 直接访问/templates/index.html。 (即通过输入127.0.0.1/templates/index.html)。点击'点击此处'打开一个消息框。

2.)失败: 从Slim访问index.php文件(注意:我没有在web服务器上激活mod_rewrite - 所以我使用index.php /.../作为URI,即127.0.0.1 /index.php/testid)。该网站加载正确,但如果我点击'点击这里'没有任何反应。

我已经尝试过:src =“../ dependency.js”,src =“../ templates/dependency.js”的不同变体,将index.html改为一个php文件并使用src =“$ webroot /templates/dependency.js“ - 但没有任何工作。任何想法如何解决这个问题?

回答

3

我觉得你很困惑你通常会如何使用Slim(或者像Silex这样的其他similat Microframework)。像JS/CSS/images这样的资源不应该对你的路由URL有意义,因为路由的url不会直接映射到基于文件系统的资源。应该是绝对的。您的设置应该是这个样子:

Slim/ 
templates/ 
    index.html 
    whatever.html 
images/ 
js/ 
    /dependency.js 
css/ 

所以所有的JS引用应该是这个样子:

src="/js/dependency.js"

除非你想写某种特殊的控制器就可以提供正确的资源基于模板或某些东西。但是如果您的应用程序布局足够复杂以至于需要这样做,那么您应该使用更像Symfony2或ZF的东西,它具有封装完整功能集的模块/捆绑包的概念。

此外,您不应该能够通过URL公开访问模板,因为这些只能由您的Slim控制器提供。事实上,我通常不会在文档根目录中有模板。我的正常设置通常看起来是这样的(public将是Web服务器文档根目录):

Slim/ 
templates/ 
    index.html 
public/ 
    index.php 
    js/ 
    images/ 
    css/ 
+0

谢谢,你说得对!这帮助了我很多。 – Constantin 2013-02-23 11:05:22