marko-js / marko

A declarative, HTML-based language that makes building web apps fun
https://markojs.com/
MIT License
13.28k stars 641 forks source link

how to compile at runtime #1640

Closed rubiin closed 3 years ago

rubiin commented 3 years ago

I used to compile handlebars at runtime as handlebar.compile(template) How do i do this in marko

rubiin commented 3 years ago

I am trying to generate pdf from marko file. For handlebars, heres my code:

const template = Handlebars.compile(htmlTemplate);

        const result = template(data);
        // We can use this to add dyamic data to our handlebas template at run time from database or API as per need. you can read the official doc to learn more https://handlebarsjs.com/
        const html = result;

        // we are using headless mode
        const browser = await puppeteer.launch({
            headless: true,
            args: ['--no-sandbox'],
        });

        const page = await browser.newPage();

        // We set the page content as the generated html by handlebars
        await page.setContent(html);

        // we Use pdf function to generate the pdf in the same folder as this file.
        await page.pdf({
            path: 'usage-report.pdf',
            format: 'A4',
            printBackground: true,
            margin: {
                left: '0px',
                top: '0px',
                right: '0px',
                bottom: '0px',
            },
        });
    },
DylanPiercey commented 3 years ago

@rubiin with Marko@5 there exists a @marko/compiler package for this. You can see the API definitions in our type definition file (https://github.com/marko-js/marko/blob/master/packages/compiler/index.d.ts).

Having said that your mileage may vary with this since some aspects of Marko expect that it is being compiled within a bundler or nodejs context.