display git branch in zsh without ohmyzsh

I’m currently using zsh as my shell and I wanted a way to display the current git branch without having to install ohmyzsh etc. I followed this guide, with some minor mods to get it working exactly how I wanted:

Create a bash function that gets the current branch from the current working directory and add to ~/.zshrc

function git_branch() {
    branch=$(git symbolic-ref HEAD 2> /dev/null | sed "s|refs/heads/||g")
    if [[ $branch == "" ]]; then
        :
    else
        echo "($branch) "
    fi
}

In order to evaluate the branch after every command we need to move our variable for the prompt PS1 into the precmd hook so that we get the branch before displaying the prompt:

precmd() {
  export PS1="%{$(tput setaf 114)%}%n%{$(tput setaf 114)%}@%{$(tput setaf 114)%}%m %{$(tput setaf 38)%}%1~ %{$(tput sgr0)%}$(git_branch)> "
}