有没有人试过和CakePHP一起使用TinyButStrong?我没有TinyButStrong的先验知识,但似乎是一个从模板生成Word文档的好方法。但我不确定如何将其与CakePHP应用程序集成。
感谢您的任何想法/建议。
最好的问候,托尼。
发布于 2011-12-18 09:43:51
我假设您指的是带有OpenTBS插件的TinyButStrong,该插件可以使用模板合并DOCX (以及其他Ms Office和OpenOffice文档)。
这是一种在CakePHP控制器中添加导出操作的方法,该方法旨在生成要下载的Docx。
以下代码适用于CakePHP版本1.3,未使用版本2.0进行测试。
步骤:
1)在厂商目录下子目录下添加TBS和OpenTBS类:
vendors/tbs/tbs_class.php
vendors/tbs/tbs_plugin_opentbs.php
2)创建一个简化TBS +OpenTBS准备的CakePHP helper:
app/views/helpers/tbs.php
<?php
class TbsHelper extends AppHelper {
function getOpenTbs() {
App::import('Vendor', 'tbs/tbs_class');
App::import('Vendor', 'tbs/tbs_plugin_opentbs');
$tbs = new clsTinyButStrong; // new instance of TBS
$tbs->Plugin(TBS_INSTALL, OPENTBS_PLUGIN); // load OpenTBS plugin
return $tbs;
}
}3)现在在控制器中添加一个新的"export“操作,它应该生成Docx:
app/controllers/example_controller.php
<?php
class ExamplesController extends AppController {
var $name = 'Examples';
function export() {
// Stop Cake from displaying action's execution time, this can corrupt the exported file
// Re-ativate in order to see bugs
Configure::write('debug',0);
// Make the Tbs helper available in the view
$this->helpers[] = 'Tbs';
// Set available data in the view
$this->set('records', $this->Example->find('all'));
}
}4)最后一件事是创建相应的视图。不要忘记将您的DOCX模板放在与视图相同的文件夹中。
app/views/examples/export.ctp (下图)
app/views/examples/export_template1.docx (使用Ms Office构建)
<?php
ob_end_clean(); // Just in case, to be sure
// Get a new instance of TBS with the OpenTBS plug-in
$otbs = $tbs->getOpenTbs();
// Load the DOCX template which is supposed to be placed in the same folder
$otbs->LoadTemplate(dirname(__FILE__).'/export_template1.docx');
// Merge data in the template
$otbs->MergeBlock('r', $records);
// End the merge and export
$file_name = 'export.docx';
$otbs->Show(OPENTBS_DOWNLOAD, $file_name);
exit; // Just in case, to be sureTinyButStrong提供了合并全局变量的功能,但建议不要在CakePHP中使用此功能。相反,您应该对视图的控制器设置的数据使用MergeBlock()和MergeField()。
如果遇到bug,不要忘记禁用这行代码
Configure::write('debug', 0);这将向您显示CakePHP错误。否则,CakePHP将隐藏所有错误。
不要忘记,OpenTBS也有一个调试模式。如果需要,请参阅manual。
您还可以将其设置为lib (在应用程序中的任何位置使用)。
https://stackoverflow.com/questions/8547192
复制相似问题