【发布时间】:2011-12-29 13:10:56
【问题描述】:
我尝试将用户定义的 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 或 Google 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>
可能有人可以提出更美丽的解决方案?
【问题讨论】:
标签: html playframework