GrapesJS / grapesjs

Free and Open source Web Builder Framework. Next generation tool for building templates without coding
https://grapesjs.com
BSD 3-Clause "New" or "Revised" License
22.36k stars 4.05k forks source link

[QUESTION] Add html, css and js to Block Manager #2596

Closed cristianumali22 closed 4 years ago

cristianumali22 commented 4 years ago

[QUESTION]

Hi! I'm retrieving dynamic html,css and js codes from the database. How can I create Blocks with this? Currently, this is my code,


    editor.BlockManager.add($aBlock['name'], {
        id: $aBlock['name'],
        label: $aBlock['name'],
        category: $aBlock['category'],
        content: $aBlock['html'],
        style: $aBlock['css'],
        script: $aBlock['css'],
      });

But its not working. Please help. Thank you.
pouyamiralayi commented 4 years ago

@cristianumali22 please consider putting both your html and css inside the content property like this:

content: '<div></div><style></style>'

for including scripts, you must define a new component type and then proceed to component & js Cheers!

cristianumali22 commented 4 years ago

Hi @pouyamiralayi , thus, doing, content: '<div></div><style></style>' will seperate the HTML from CSS in the download code feature of GrapesJS?

Note that in every blocks of code, there is different HTML, CSS and JS. Is the css of, example block_1, will not affect the style of block_2?

pouyamiralayi commented 4 years ago

@cristianumali22 yes you are right! in that case change your approach to defining component types, by that you have the chance to define your component specific css inside style property. Cheers!

cristianumali22 commented 4 years ago
const myNewComponentTypes = editor => {
  editor.DomComponents.addType(/* API for component type definition */);
};

const editor = grapesjs.init({
  container : '#gjs',
  // ...
  plugins: [ myNewComponentTypes ],
});

@pouyamiralayi , base on the documentation, it says that "The first rule of defining new component types is to place the code inside a plugin". But when I use the code above, it says undefined variable editor. Because it is used before grapesjs even declared. Is it also possible without creating new file for components?

pouyamiralayi commented 4 years ago

@cristianumali22 your code looks fine and it is not executed before grapesjs initialization because you are passing the reference and not actually calling it! i suggest using the grapesjs cli because it is doing all the setups for you and providing you with a nice and clean environment. Cheers!