0

I'm trying to display some code on my website. I'm using prism which is working well, however, I'm eventually going to have to store the code I'm trying to present in a mongodb database. Right now I'm having trouble figuring out how to save the code as variable codeSnippet and presenting it. How do I do this?

What it is suppose to look like

class DispalyCodeExample extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    Prism.highlightAll();
  }

  render() {
    return (
      <pre>
        <code className="language-javascript">
          {`
let animals = {
  cow: 'moo',
  mouse: 'squeak'
}
let mouse = 'cow';
let x = animals[mouse];
          `}
        </code>
      </pre>
    );
  }
}

My attempt that's not working - due to my codeSnippet variable

class DispalyCodeExample extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    Prism.highlightAll();
  }

  render() {
    const codeSnippet =  {
    let animals = {
      cow: 'moo',
      mouse: 'squeak'
    }
    let mouse = 'cow';
    let x = animals[mouse];
              };
    return (
      <pre>
        <code className="language-javascript">
         {codeSnippet}
        </code>
      </pre>
    );
  }
}

1 Answer 1

1

I would base64 encode the entire class, then store it in MongoDB. When you're ready to display on a web page, base64 decode the block of your source code. This way, all source code won't be changed to HTML characters. All variables and functions will be preserved.

Sign up to request clarification or add additional context in comments.

2 Comments

That seems to be a great solution, however, when used with prismjs the styling isn't being applied. It doesn't seem to recognise the opening {` and closing `} brackets. Any suggestions.
all good figured out I can't save those brackets into my base64 code. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.