0

I'm trying to build a quick and dirty static site generator for myself.

Let's say I have this test.html file:

{title}
{downloadpath}

This is my current.json where I get the values i want to replace:

{
    "id": 123,
    "album" : [{
        "title": "Test EP",
        "albumid": 1234,
        "path": "test.zip"
     }]
}

My replacement function looks like this:

    // Iterate through JSON object and replace
    function iterate(obj) {
        for (var property in obj) {
            if (obj.hasOwnProperty(property)) {
                if (typeof obj[property] == "object")
                    iterate(obj[property]);
                else
                console.log("replace {" + property + "} with " + obj[property] )
                htmldata.replace(/\{property\}/g, obj[property]);
            }
        }
    }
    iterate(json)
    var result = htmldata

    console.log(result)

    // Write new HTML
    fs.writeFile("test-" + json.id + ".html", result, 'utf8', function (err) {
        if (err) {
            return console.log(err);
        }
    });

and if I run it it works like this:

replace {id} with 123
replace {title} with Test EP
replace {albumid} with 1234
replace {path} with test.zip
{title}
{path}

and you can see the problem right there. I think it's always replacing the edited file with the input file so I don't see any changes. I can't figure it out and if someone could point me in the right direction I'd be grateful.

Thanks!

1
  • you can simply work with something like underscore's _.template function and skip the self-rolling-template-function Commented Nov 8, 2013 at 19:55

1 Answer 1

3

Not using braces around your if statements will lead to subtle bugs!

You want:

if (typeof obj[property] == "object") {
    iterate(obj[property]);
} else {
    console.log("replace {" + property + "} with " + obj[property] )
    htmldata.replace(/\{property\}/g, obj[property]);
}

Otherwise the replace will run every time regardless of the condition on the if.

Second thing: your regex tries to match the literal string "{property}". Instead, try this:

htmldata.replace(new RegExp("{" + property + "}", "g"), obj[property]);

Third thing: you're not assigning the result of the replace back to htmldata. So you need to do this:

htmldata = htmldata.replace(new RegExp("{" + property + "}", "g"), obj[property]);
Sign up to request clarification or add additional context in comments.

3 Comments

the result of htmldata.replace() needs to be reassigned as well?
@pero Ah yes, it does. I should write out the whole line - I just wrote the replace part. Editing now!
Thanks a lot! It's working perfectly now, I was literally looking at this code for hours now.

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.