简体   繁体   English

将TWIG输出发送到Symfony中的zip进行模板化

[英]Sending TWIG output to a zip in Symfony for Templating

I need to create a system that will be able to output a template (a zip with an index.html with all js, css, img etc files as required) based on a set of options (include menu 1, use small footer etc). 我需要创建一个能够基于一组选项(包括菜单1,使用小页脚等)输出模板(根据需要包含所有js,css,img等文件的index.html的zip文件)的系统。

So I can put code blocks in so it would not be hard to actually output to the browser the required look, but what if I want to save the rendered html (and this means we would need to change the locations of files like js etc) to a zip instead? 因此,我可以放入代码块,这样实际上就不会很难将所需的外观输出到浏览器,但是如果我想保存渲染的html会怎样(这意味着我们需要更改js等文件的位置)改成拉链?

Any ideas? 有任何想法吗? At the moment I'm thinking it would all need to be processed in PHP anyhow (the controller) and TWIG may not be too helpful, but that would make it more complicated. 目前,我认为无论如何都需要使用PHP(控制器)进行处理,而TWIG可能并没有太大帮助,但这会使它变得更加复杂。

So I worked this one out, here is the controller to output the required twig zipped: 所以我解决了这个问题,这里是控制器,用于输出所需的压缩过的树枝:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    /**
     * @Route("/{variableName}", name="homepage"})
     */
    public function indexAction($variableName = "Default")
    {
        //do whatever you need to get the template correct

        //send rendered TWIG to a variable
        $renderedhtml = $this->render('default/index.html.twig', [
            'variableName' => $variableName
        ])->getContent();

        $zipName = "template.zip";
        $main = $this->get('kernel')->getRootDir() . '/../web/workingdir/';
        $vername = time(); //we use the exact time to get a unique dir name

        //remove any projects older than a few minutes (5 in this case)
        $dirHandle = opendir($main);
        while($item = readdir($dirHandle)){
            if(is_dir($main . $item) && $item != '.' && $item != '..') {
                if ( ( ( $item + ( 60 * 5 ) ) < $vername ) ) {
                    system('/bin/rm -rf ' . escapeshellarg($main . $item));
                }
            }
        }

        //make the project dir and populate it with files (in this case just the template as index.html, you would want to copy all other files here though)
        mkdir($main.$vername);
        file_put_contents($main.$vername."/index.html", $renderedhtml);

        //create the zip
        $zip = new \ZipArchive();
        $zip->open($zipName,  \ZipArchive::CREATE);
        $zip = $this->createZip($zip, $main.$vername);
        $zip->close();

        //get the zip ready to return
        header('Content-Type', 'application/zip');
        header('Content-disposition: attachment; filename="' . $zipName . '"');
        header('Content-Length: ' . filesize($zipName));
        readfile($zipName);
    }

    // Create a zip with zip object and root dir params (find and include sub-dirs with content)
    private function createZip($zip, $source) {
        $source = str_replace('\\', '/', realpath($source));

        if (is_dir($source) === true) {
            $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source), \RecursiveIteratorIterator::SELF_FIRST);

            foreach ($files as $file) {
                $file = str_replace('\\', '/', $file);

                if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
                continue;

                $file = realpath($file);

                if (is_dir($file) === true)
                {
                    $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
                }
                else if (is_file($file) === true)
                {
                    $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
                }
            }
        }
        return $zip;
    }
}

Once you get it to this stage, you will just have to add any other required files into the working dir, but I think that could be done under a different issue, this one is about getting the website into a html in a zip. 一旦进入此阶段,您只需要将其他所有必需的文件添加到工作目录中即可,但是我认为可以在其他问题下完成,这是将网站转换为zip格式的html。

Hope this helps someone. 希望这对某人有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM