CONNECT-platform / codedoc

Create beautiful modern documentation websites.

Home Page:https://codedoc.cc

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

parsing component content as js code

nakednous opened this issue · comments

How to parse my component content var as plain js code without html tags (so that the blocks gets executed as a script)? So far I tried:

<script> ${content} </script>

see this line, but I got:

<script> [object HTMLParagraphElement],[object HTMLParagraphElement],[object HTMLParagraphElement] </script>

See an example page and its result.

I did not fully understand what you want to do here. As you can see, content parameter is an array of DOM nodes (which are the children passed to the component). If you want to turn it into HTML string, I would recommend something like this:

const htmlString = (<div>{content}</div>).innerHTML;

EDIT: I looked at your example and seems like you are trying to parse the content of the component as code, and then pass that code to a <script> tag. It is notable that contents are parsed as CODEDOC markdown by default, which might cause issue if you want them to be read as code. To that end, I suspect some solution like this should work (needs testing):

// inside your custom component
const code = (<div>{content}</div>).textContent;

return ... <script>{code}</script> ...

and usage would be like this:

> :P5 ...
>
> ```js
> function someFunction() {
>    ...
> }
> // or any other code
> ```

This solution hinges on encapsulating code in markdown code, so that it is not parsed as markdown before being passed to your component.

Yeah that's what I meant. Have tried:

let code: string = (<div>{content}</div>).innerHTML;
code = code.replace(/<\/?[^>]+(>|$)/g, "");

which also worked, but your solution is simpler. Thanks!