我尝试将用户定义css文件插入到我的模板中。
型号:
@Entity
public class MyModel extends Model {
// Some code stuff...
/** User-defined css file. */
public Blob stylesheet;
}控制器
public class MyController extends Controller {
// Some code stuff...
/**
* Displays user-defined css file for specified instance of MyModel.
*/
public static void displayStylesheet(Long id) {
final MyModel myModel = MyModel.findById(id);
notFoundIfNull(myModel);
response.setContentTypeIfNotSet(myModel.stylesheet.type());
if (myModel.stylesheet.exists()) {
renderBinary(myModel.stylesheet.getFile());
}
}
/**
* Displays page, that contains user-defined css file
* for specified instance of MyModel.
*/
public static void index(Long id) {
render(id);
}
}视图
#{extends 'main.html' /}
#{set 'styles'}
<link rel="stylesheet" href="@{MyController.displayStylesheet(id)}" />
#{/set}
<p>This page contains user-defined stylesheet.</p>当我尝试通过GET请求显示样式表时,一切都很正常:
http://localhost:9000/mycontroller/displaystylesheet?id=1188但FireBug或谷歌Chrome开发者的面板并不像源码那样显示这种风格。
更新:
我找到了解决方案,但它不是那么完美。控制器中的代码:
/**
* Displays page, that contains user-defined css file
* for specified instance of MyModel.
*/
public static void index(Long id) {
final MyModel myModel = MyModel.findById(id);
String styles = "";
File stylesheet = myModel.stylesheet.getFile();
try {
FileInputStream stream = new FileInputStream(stylesheet);
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
styles = Charset.defaultCharset().decode(bb).toString();
}
finally {
stream.close();
}
}
catch (IOException ioe){
throw new RuntimeException(ioe);
}
render(id, styles);
}它会将所有样式放入一个字符串styles中。然后我们可以在模板中呈现它:
<style type="text/css">
${styles}
</style>也许有人可以提出更漂亮的完整解决方案?
发布于 2011-12-29 21:18:32
您遇到的问题是,由于您使用的是renderBinary,所以内容类型被返回为application/binary,因此浏览器忽略了它,因为它不是"text/css"类型。
在使用renderBinary时,renderBinary代码根据使用的参数以一系列不同的方式设置contentType。当您使用File时,它将根据文件名确定内容类型。
所以,如果你能保证你的文件名是CSS类型的,那么当它执行MimeType.getContentType(filename);时,它会相应地设置contentType。
否则,您可以将代码更改为如下所示
public static void displayStylesheet(Integer id) {
// ... read css data from file into a String
String cssTextData = readCSSFromFile(); // <-- You can use the method you have used in your update here
response.contentType = "text/css";
renderText(cssTextData);
}https://stackoverflow.com/questions/8668305
复制相似问题