3

有人尝试过将 TinyButStrong 与 CakePHP 一起使用吗?我对 TinyButStrong 没有先验知识,但似乎是从模板生成 Word 文档的好方法。但我不确定如何将它与 CakePHP 应用程序集成。

感谢您的任何想法/建议。

最好的问候,托尼。

4

1 回答 1

7

我猜你的意思是带有OpenTBS插件的 TinyButStrong,它可以使用模板合并 DOCX(以及其他 Ms Office 和 OpenOffice 文档)。

这是一种在 CakePHP 控制器中添加导出操作的方法,该控制器旨在生成要下载的 Docx。

以下代码适用于 CakePHP 1.3 版,未在 2.0 版中测试。

脚步 :

1) 在 vendor 目录的子目录下添加 TBS 和 OpenTBS 类:

供应商/tbs/tbs_class.php
供应商/tbs/tbs_plugin_opentbs.php

2) 创建一个 CakePHP 助手,它将简化 TBS + OpenTBS 的准备工作:

应用程序/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) 现在在控制器中添加一个新的“导出”动作,它应该生成 Docx:

应用程序/控制器/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 (与 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 sure

TinyButStrong 提供了合并 PHP 全局变量的功能,但建议不要在 CakePHP 中使用此类功能。相反,您应该将 MergeBlock() 和 MergeField() 与控制器为视图设置的数据一起使用。

如果您遇到错误,请不要忘记禁用该行

Configure::write('debug', 0);

这将向您显示 CakePHP 错误。否则 CakePHP 将隐藏所有错误,包括 PHP 错误。

不要忘记 OpenTBS 也有调试模式。如果需要,请参阅手册。

你也可以把它变成一个库(在你的应用程序的任何地方使用)。

于 2011-12-18T01:43:50.793 回答