givanz / VvvebJs

Drag and drop page builder library written in vanilla javascript without dependencies or build tools.
https://www.vvveb.com/vvvebjs/editor.html
Apache License 2.0
6.91k stars 1.59k forks source link

PHP code in component #283

Closed vinumweb closed 8 months ago

vinumweb commented 1 year ago

Hi again @givanz New day new question i guess :)

How can i include PHP code in a component. The site is .php

givanz commented 1 year ago

Hi

You can't include php code in a component, components are written in javascript. You can call a php file with ajax and get the contents when initializing the component by using the init function.

Vvveb.Components.add("elements/section", {
    nodes: ["section"],
    name: "My component",
    init: function (node)
    {
               $.ajax({
          method: "POST",//or use get
          url: "database.php",
          data: { id: url } //add your post/get parameters
        })
          .done(function( data ) {
                       //replace the content of the selected element in editor with the contents from php
            $(node).html(data);
          });
    },  
}); 

The editor can only edit html content, it can't edit other formats like php or templates such as twig, smarty etc.

vinumweb commented 1 year ago

Hi @givanz . Thanks for the answer. Waht im trying to do is do an "include" function in php for a navigation bar. How do i do that in a element?

givanz commented 1 year ago

You want something like dynamic components, where the content that is inserted in the page on drag and drop comes from php?

Edit editor.html and add <script src="dynamic-components.php"></script> bellow <script src="libs/builder/components-widgets.js"></script>

<!-- components-->
<script src="libs/builder/components-widgets.js"></script>  
<script src="dynamic-components.php"></script>  <!-- Add this line -->

Then create a new file dynamic-components.php in the same folder as editor.html with the following content:

Vvveb.ComponentsGroup['My components'] =
["dynamic/navigation", "dynamic/myothercomponent"];

Vvveb.Components.extend("_base", "dynamic/navigation", {
    classes: ["navigation"],
    image: "icons/navbar.svg",
    html: `<?php 
        //echo include('navigation.php');
        echo '<div class="navigation">This content is added from php!</div>';
    ?>`,
    name: "My navigation",
    properties: [{
        name: "Background Color",
        key: "background-color",
    htmlAttr: "style",
        inputtype: ColorInput,
    }, {
        name: "Text Color",
        key: "color",
    htmlAttr: "style",
        inputtype: ColorInput,
    }],
});